Java – String v/s StringBuffer

In this article, we will discuss difference between String and StringBuffer in detail with examples

1. String v/s StringBuffer:

String

StringBuffer

String is immutableStringBuffer is very similar to String class with only difference is that, it is mutable
It means that, once new string literal is created, it cannot be changed for modification or altercationAfter creating StringBuffer object, it can be altered or modified, as and when required depending on the requirement
For every operation on String, a new String literal is created inside String Constant Pool (SCP)For every operation on StringBuffer like append, insert, reverse or replace same StringBuffer object is returned
All string literals are stored inside String Constant Pool (SCP)StringBuffer objects created are stored inside heap memory like any Java objects
String consumes more memory;

 

Since it creates new string literal every-time inside String Constant Pool, after any concatenation operation

StringBuffer consumes very less memory as compared to String;

 

Since it doesn’t create any new object and instead returns same StringBuffer object after performing operations

Performance-wise, String is very slow when there are more number of concatenation operation

 

We will see an example to understand this scenario

Performance-wise, StringBuffer is very fast when there are more number of append operation

 

We will see an example to understand this scenario

Q) When to use String and StringBuffer ?

String:

  • When there are not many modification on same string and it is going to remain constant over a period of time, then String is preferred
  • In addition, when using string provides thread-safety

StringBuffer:

  • In a multi-threaded application, StringBuffer need to be preferred as it ensure thread-safety
  • Though it will be slower when compared with StringBuilder but ensures data-consistency by not allowing multiple threads to operate at the same time concurrently
  • Because every time lock has to be acquired before any operation on StringBuffer object and only after releasing the lock, 2nd thread can take charge

2. Example on performance of String v/s StringBuffer:

StringVsStringBufferPerformanceTest.java

package in.bench.resources.performance.test;

public class StringVsStringBufferPerformanceTest {

	public static void main(String[] args) {

		// counter
		int iCount = 0;
		long startTime = 0;
		long endTime = 0;

		// sample String
		String testStr = "";

		// START time for String concatenation
		startTime = System.currentTimeMillis();

		// Test 1: for String concatenation
		while(iCount < 20000) {

			testStr = testStr + "BenchResources.Net";

			// increment counter by 1
			iCount++;
		}

		// END time for String concatenation
		endTime = System.currentTimeMillis();

		System.out.println("The time taken for "
				+ "String concatenation is : "
				+ (endTime - startTime) + "ms");

		// sample StringBuffer
		StringBuffer sbf = new StringBuffer();

		// assign ZERO to counter
		iCount = 0;

		// START time for StringBuffer append() operation
		startTime = System.currentTimeMillis();

		// Test 2: for StringBuffer append
		while(iCount < 20000) {

			sbf.append("BenchResources.Net");

			// increment counter by 1
			iCount++;
		}

		// END time for StringBuffer append() operation
		endTime = System.currentTimeMillis();

		System.out.println("The time taken for "
				+ "StringBuffer append() is : "
				+ (endTime - startTime) + "ms");
	}
}

Output:

The time taken for String concatenation is : 11438ms
The time taken for StringBuffer append() is : 2ms

Note: There will be slight difference in the result on executing at various times

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - StringBuffer v/s StringBuilder
Java - How to convert String to StringBuilder and vice-versa ?