Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed issue while appending strings

Whenever I try to add the numbers in string like:

String s=new String();

 for(int j=0;j<=1000000;j++)

    s+=String.valueOf(j);

My program is adding the numbers, but very slowly. But When I altered my program and made it like:

StringBuffer sb=new StringBuffer();

for(int j=0;j<=1000000;j++)

sb.append(String.valueOf(j));

I got the result very quickly. Why is that so?

like image 337
Stardust Avatar asked Jan 13 '10 09:01

Stardust


1 Answers

s+=String.valueOf(j); needs to allocate a new String object every time it is called, and this is expensive. The StringBuffer only needs to grow some internal representation when the contained string is too large, which happens much less often.

It would probably be even faster if you used a StringBuilder, which is a non-synchronized version of a StringBuffer.

One thing to note is that while this does apply to loops and many other cases, it does not necessarily apply to all cases where Strings are concatenated using +:

String helloWorld = getGreeting() + ", " + getUsername() + "!";

Here, the compiler will probably optimize the code in a way that it sees fit, which may or may not be creating a StringBuilder, since that is also an expensive operation.

like image 101
Thomas Lötzer Avatar answered Sep 28 '22 00:09

Thomas Lötzer