0

Possible Duplicate:
what is the difference between String and StringBuffer in java?

When I test a function using StringBuffer and String. When I use StringBuffer, I get the java.lang.OutOfMemoryError within the 2 or 3 secound.But, when I use String, I did not get java.lang.OutOfMemoryError error until one minutes. What different them, I don't know exactly.

public void print() {
    StringBuffer buffer = new StringBuffer();
    double result = 1.0 / 7.0;
    buffer.append(result);
    while (result != 0) {
        result = result % 7.0;
        buffer.append(result);
    }
    System.out.println(buffer.toString());
}


public void print() {
    String st = "";
    double result = 1.0 / 7.0;
    st = st + result;
    while (result != 0) {
        result = result % 7.0;
        st = st + result;
    }
    System.out.println(st);
} 
5
  • 3
    Possible duplication of stackoverflow.com/questions/2439243/… Commented Sep 17, 2012 at 11:31
  • It will be faster. I don't know why I get Out of Memory with StringBuffer. Now, I am taking reference in stackoverflow.com/questions/2439243/… Commented Sep 17, 2012 at 11:37
  • StringBuffer is faster so you may run out of memory faster. You should check how many results got stored in each case to see if it's the problem with speed difference or the memory usage difference between String and StringBuffer Commented Sep 17, 2012 at 11:37
  • I would add that StringBuffer was replaced in Java 5.0 eight years ago by StringBuilder but String is still used today. Commented Sep 17, 2012 at 11:49
  • This will make you understand the concepts clearly Commented Jul 25, 2013 at 6:39

1 Answer 1

2

That's probably because when you use StringBuffer, your while loop executes 20 to 30 times faster than when you create new String at each iterations : as a consequence, you ran out of memory sooner.

BTW, never perform concatenation operations in a loop with String objects. Use StringBuilder instead (not StringBuffer as it is slightly slower than StringBuilder as its methods are synchronized).

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

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.