tags:

views:

100

answers:

4

Hi,

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?

+6  A: 

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.

Thomas Lötzer
+1 for StringBuilder. You could also pre-allocate memory for it (parameter to the constructor).
Thilo
+1  A: 

Because s += "string" creates a new instance. A String is immutable. StringBuffer or StringBuilder adds the String without creating a new instance.

bertolami
+1  A: 

In Java as in .NET Strings are immutable. They cannot be changed after creation. The result is that using the +operator will create a new string and copy the contents of both strings into it.

A StringBuffer will double the allocated space every time it runs out of space to add characters. Thus reducing the amount of memory allocations.

Yannick M.
+1  A: 

Take a look at this, from the Javaspecialists newsletter by Heinz Kabutz:

http://www.javaspecialists.eu/archive/Issue068.html

and this later article:

http://java.sun.com/developer/technicalArticles/Interviews/community/kabutz_qa.html

David Rodríguez - dribeas