6

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?

3
  • joelonsoftware.com/articles/fog0000000319.html Commented Jan 13, 2010 at 9:38
  • May I suggest you to read Effective Java amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683 This book will cover basic knowledge of Java programming. If you have further question, you can still go back here, of course Commented Jan 13, 2010 at 9:44
  • It'll get faster still if you pre-size the StringBuffer: StringBuffer sb = new StringBuffer(5888896); Then it might get slightly faster again if you change to StringBuilder. Incidentally, you can just use sb.append(j); to append the number. Commented Jan 13, 2010 at 20:21

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for StringBuilder. You could also pre-allocate memory for it (parameter to the constructor).
1

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

Comments

1

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.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.