java中的字符串初始化和连接

Sha*_*yaz 3 java performance

在我的应用程序中一切正常,但我想提高性能并优化我的代码.

这两个中哪一个更好

1.initialisation

String str1=new String("Hello");
String str2="Hello";
Run Code Online (Sandbox Code Playgroud)

2.concatenation

System.out.println(s1 + s2);
System.out.println(new StringBuffer(S1).append(s2));
Run Code Online (Sandbox Code Playgroud)

See*_*ose 6

首先,不要提高性能并优化代码,除非您首先分析您的应用程序并实现了这样做的非常好的理由.

其次,对于String变量的初始化,最好不要使用String构造函数.使用常量字符串(与str2一样),Java可以将String对象从String池中拉出.

第三,不要使用StringBuffer进行连接.请改用StringBuilder.StringBuffer的方法是同步的,这会显着降低应用程序的速度.实际上,你的两种连接几乎是相同的,因为所有现代编译器都创建了字节代码,它使用StringBuilder来表达像"s1 + s2"这样的表达式.