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"