您显示的两个片段几乎相同。
String
Java 中的a是不可变的;它不能改变。使用连接运算符 ( +
) 时,编译器实际上使用StringBuilder
例如,您的第二个片段变为:
String makeDate = new StringBuilder()
.append(now.year)
.append("")
.append(now.month)
.append("")
.append(now.monthDay)
.toString();
您可以查看生成的字节码以了解这一点。Java 附带一个程序javap
,可以让您查看已编译的.class
.
我创建了一个简单main()
的提供最小字节码:
public static void main(String[] args)
{
String makeDate = Integer.toString(1) + Integer.toString(1) + Integer.toString(1);
System.out.println(makeDate);
}
产生:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=1
0: new #2 // class java/lang/StringBuilder
3: dup
4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
7: iconst_1
8: invokestatic #4 // Method java/lang/Integer.toString:(I)Ljava/lang/String;
11: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
14: iconst_1
15: invokestatic #4 // Method java/lang/Integer.toString:(I)Ljava/lang/String;
18: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: iconst_1
22: invokestatic #4 // Method java/lang/Integer.toString:(I)Ljava/lang/String;
25: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
28: invokevirtual #6 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
31: astore_1
32: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
35: aload_1
36: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
39: return
相对:
public static void main(String[] args)
{
int i = 1;
String makeDate = i + "" + i + "" + i;
System.out.println(makeDate);
}
产生:
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=3, args_size=1
0: iconst_1
1: istore_1
2: new #2 // class java/lang/StringBuilder
5: dup
6: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
9: iload_1
10: invokevirtual #4 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
13: ldc #5 // String
15: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: iload_1
19: invokevirtual #4 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: ldc #5 // String
24: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
27: iload_1
28: invokevirtual #4 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
31: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
34: astore_2
35: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
38: aload_2
39: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
42: return
从技术上讲,后者在某种规模上可能更快,几乎无法测量(< 1ns),但对于所有实际目的来说,这并不重要;使用任何你喜欢的。