Is there a "fastest technique" in Java to build Strings?

In Java, I usually make a String by doing the following:

String foo = "123456";

However, my lecturer insisted on constructing a String using the formatting technique, as follows:

String foo = String.format("%s", 123456);

Is a lot faster.

He also claims that utilizing the StringBuilder class is quicker.

StringBuilder sb = new StringBuilder();
String foo = sb.append(String.format("%s", 123456)).toString();

Which, if any, is the quickest way for creating a String? Before posting a question here, I’ve looked into other resources like Scaler, GFG & Wikipedia and it occurred to me that StringBuilder is the fastest among all the other String classes such as String and StringBuffer. Am I correct or not?

This feels like a micro optimization that doesn’t meaningfully change the runtime of your program.

Do you have any reason to think that your teacher is wrong or lying? Did the teacher explain why those other methods are faster? What did you find when you did your own research?

1 Like