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);
} 
Community
  • 1
  • 1
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131
  • 3
    Possible duplication of http://stackoverflow.com/questions/2439243/what-is-the-difference-between-string-and-stringbuffer-in-java – gigadot Sep 17 '12 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 http://stackoverflow.com/questions/2439243/what-is-the-difference-between-string-and-stringbuffer-in-java – Zaw Than oo Sep 17 '12 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 – gigadot Sep 17 '12 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. – Peter Lawrey Sep 17 '12 at 11:49
  • [This](http://www.acquireandinspire.org/2013/01/string-string-builder-string-buffer.html) will make you understand the concepts clearly – roger_that Jul 25 '13 at 06:39

1 Answers1

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).

Alexandre Dupriez
  • 3,026
  • 20
  • 25