When to Use StringBuffer and StringBuilder class in Java Programming

We should use StringBuffer for multi-threaded java program or else Stringbuilder class. The difference between StringBuffer and StringBuilder class in java is that StringBuffer is synchronized, whereas, StringBuilder is not.

In multithreading application, if a buffer is shared among multiple threads, then we should consider using StringBuffer as all of its methods are synchronized and hence thread safe. Otherwise, consider String Builder.

Note that if a buffer is not shared, always use StringBuilder in multithreaded application also, to avoid performance issue (speed). In fact, performance difference we can see only if the buffer is called repeatedly in a loop.

Lets do the performance test using StringBuffer and StringBuilder class with a java code example. We will use a huge loop for both class to add  a string. Note that we will be adding the same string i.e. “Performance Testing” for both classes.

As StringBuffer is synchronized, it will take more time to execute than StringBuilder.

//Execution time test of StringBuffer and StringBuilder class
public class PerformanceTest {

	public static void main(String[] args) {

		// Time taken by String Buffer class
		long startTime = System.currentTimeMillis();
		StringBuffer sBuffer = new StringBuffer("TEST PERFORMANCE");
		for (int i = 0; i < 50000; i++) {
			sBuffer.append("Performance Testing");
		}
		System.out.println("Execution time of StringBuffer: "
				+ (System.currentTimeMillis() - startTime) + "ms");

		// Time taken by String Builder
		startTime = System.currentTimeMillis();
		StringBuilder sBuilder = new StringBuilder("TEST PERFORMANCE");
		for (int i = 0; i < 50000; i++) {
			sBuilder.append("Performance Testing");
		}
		System.out.println("Execution time for StringBuilder: "
				+ (System.currentTimeMillis() - startTime) + "ms");
	}
}

OUTPUT:

Execution time of StringBuffer: 31ms
Execution time for StringBuilder: 16ms

Note that output may vary but execution time of String buffer class should always be greater than Strung builder

Related Posts