String initialization and connection in Java

Everything is fine in my application, but I want to improve performance and optimize my code

Which of the two is better

1.initialisation

String str1=new String("Hello");
String str2="Hello";

2.concatenation

System.out.println(s1 + s2);
System.out.println(new StringBuffer(S1).append(s2));

Solution

First, don't improve performance and optimize your code unless you first analyze your application and implement a very good reason to do so

Secondly, for the initialization of string variables, it is best not to use string constructors Using constant strings (like STR2), Java can pull string objects out of the string pool

Third, do not use StringBuffer to connect Use StringBuilder. Instead The StringBuffer method is synchronous, which will significantly reduce the speed of the application In fact, your two connections are almost the same, because all modern compilers create bytecode, which uses StringBuilder to express expressions like "S1 S2"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>