Which one of the following is more efficient?

String str1 = "Hello " + "Guest";  // 1
String str2 = (new StringBuffer().append("Hello ")).append("Guest").toString();  //2

str1 is resolved at compile time, while str2 is resolved at runtime time with an extra StringBuffer and String. The version that can be resolved at compile time is more efficient. It avoids the overhead of creating a String and an extra StringBuffer, as well as avoiding the runtime cost of several method calls.

Related Post

No related posts

Comments

Leave a Reply




Technology