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.
So basically, using the + operator or StringBuilder.
Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.
So from this benchmark test we can see that StringBuilder is the fastest in string manipulation. Next is StringBuffer , which is between two and three times slower than StringBuilder .
If there is only one string then:
String foo = "123456";
Is fastest. You'll notice that the String.format
line has "%s%"
declared 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 call append
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With