Java – String vs StringBuffer

This article shows the difference in time taken for similar operations on a String object and StringBuffer object.

  1. String being an immutable class, it instantiates a new object each time an operation is performed on it
  2. StringBuffer being a mutable class, the overhead of object instantiation during operations is removed. Hence, the time taken for operations is less compared to String

1. String vs StringBuffer

Let us now compare the execution time taken by String class and StringBuffer class to append 10000 characters.

TimeTester.java

package com.mkyong;

public class TimeTester{

    public static void main(String[] args) {

        String aString = "";
        long before = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            aString = aString + "x";
        }
        long after = (System.currentTimeMillis());
        System.out.println("Execution Time for String: " + (after - before));

        before = System.currentTimeMillis();
        StringBuffer aStringBuffer = new StringBuffer();
        for (int i = 0; i < 10000; i++) {
            aStringBuffer.append("x");
        }
        after = (System.currentTimeMillis());
        System.out.println("Execution Time for StringBuffer: " + (after - before));

    }

}

On executing the above code, you get the below output. The output may vary depending on your processor speed. As it can be clearly seen, it takes 128 milliseconds to append 10000 Strings to a String object. Compared to which, StringBuffer takes mere 11 milliseconds to make this happen.


Execution Time for String: 128
Execution Time for StringBuffer: 11

This proves that when it comes to time StringBuffer is faster than String. However, the immutable property of String makes it thread-safe.

2. Conclusion

To conclude, one can say that StringBuffer is a better choice over String if you are well acquainted with its syntax as well as functions provided by the class. It is faster and mutable. String is limited to use for situations requiring read-only objects or require manipulation of strings.

References

  1. Why StringBuffer is faster than String
  2. String Javadocs
  3. StringBuffer Javadocs
  4. Definition as per java docs

About Author

author image
A technically sound person, oriented towards learning things logically rather than technically. It is my logical approach that has helped me learn and take up any programming language and start with coding. With a responsibility of Java based Web development professionally, I highly believe in imparting knowledge online for any technical subject that I can handle.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments