[英]Java multiline string formation
I'm by no means a java programmer, so this may seem pretty basic. 我绝不是一个java程序员,所以这看起来很基本。
Which of these are 'better' when you want to keep your code lines short. 当您想要保持代码行简短时,哪些“更好”。
String str = "First part of a string.";
str += " Second part of string.";
or 要么
String str = "First part of string." +
" Second part of string."
I guess my question is do both the += and + make a new String object? 我想我的问题是做+ =和+做一个新的String对象? If they do then neither really are better, it would just be a matter of preference.
如果他们这样做,那么两者都不会更好,这只是一个偏好问题。 The example I gave would be a good example of real world use.
我给出的例子将是现实世界使用的一个很好的例子。 I don't want a comparison of doing a concatenation 3 times to 1000 times with either method.
我不想比较使用任何一种方法进行3次到1000次连接。
Thanks 谢谢
I prefer the 2nd method. 我更喜欢第二种方法。 The reason is that the compiler will likely combine the result of the concatenation into a single string at compile time while the 1st method may be done at run-time (depending on the actual implemention.) It's a small thing unless you're doing something millions of times, however.
原因是编译器可能会在编译时将串联的结果组合成单个字符串,而第一个方法可能在运行时完成(取决于实际的实现)。除非你做某事,否则它是一件小事然而,数百万次。
The Java compiler is actually required to concatenate the second example at compile time. 实际上,Java编译器需要在编译时连接第二个示例。 See 15.28.
见15.28。 Constant Expressions and 3.10.5.
常量表达式和3.10.5。 String Literals .
字符串文字 。
Here's what I get when I compile then decompile this: 这是我编译时得到的反编译器:
public static void main(String[] args) {
String str = "First";
str += " Second";
System.out.println(str);
String str2 = "First" + " Second";
System.out.println(str2);
}
Becomes: 变为:
public static void main(String args[]) {
String s = "First";
s = (new StringBuilder()).append(s).append(" Second").toString();
System.out.println(s);
String s1 = "First Second";
System.out.println(s1);
}
So the second method is better. 所以第二种方法更好。
StringBuilder sb = new StringBuilder();
sb.append("First part");
sb.append("Second part");
System.out.print(sb.toString());
Following Java's coding conventions: 遵循Java的编码约定:
String str = "First part of string. "
+ "Second part of string.";
Make sure the '+' operator begins the next line this improves readability. 确保'+'运算符开始下一行,这提高了可读性。 Using this style allows for readable and efficient code.
使用此样式可以实现可读且高效的代码。 https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248
https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248
Hope this helps! 希望这可以帮助!
Happy coding, 快乐的编码,
Brady 布雷迪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.