Java String vs StringBuffer
This article shows the difference in time taken for similar operations on a String object and StringBuffer object.
String being an immutable class, it instantiates a new object each time an operation is performed on it
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.
Note
Read this - Why StringBuffer is faster than String
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
From:一号门
COMMENTS