I normally create a String in Java the following way:
String foo = "123456";
However, My lecturer has insisted to me that forming a String using the format method, as so:
String foo = String.format("%s", 123456);
Is much faster.
Also, he says that using the StringBuilder class is even faster.
StringBuilder sb = new StringBuilder();
String foo = sb.append(String.format("%s", 123456)).toString();
Which is the fastest method to create a String, if there even is one?
They could not be 100% accurate as I might not remember them fully.
If there is only one string then:
Is fastest. You’ll notice that the
String.formatline includes"%s"in it, so I don’t see how the lecturer could possibly think that was faster. Plus you’ve got a method call on top of it.However, if you’re building a string over time, such as in a for-loop, then you’ll want to use a StringBuilder. If you were to just use
+=then you’re building a brand new string every time the+=line is called. StringBuilder is much faster since it holds a buffer and appends to that every time you callappend.