Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "fastest way" to construct Strings in Java?

Tags:

java

string

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.

like image 758
Redandwhite Avatar asked Dec 03 '09 18:12

Redandwhite


People also ask

Which is the fastest way to concatenate many strings in Java?

So basically, using the + operator or StringBuilder.

What is the efficient way of concatenating the string in Java?

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.

Is string builder fast?

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 .


1 Answers

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.

like image 181
jasonh Avatar answered Oct 18 '22 14:10

jasonh