Site icon

Difference between StringBuilder & StringBuffer in java (example)

Class hierarchies of StringBuilder & StringBuffer

public final class StringBuilder extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
 public final class StringBuffer extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence

Few methods of StringBuffer class:

@Override
public synchronized int length() {
	return count;
}

@Override
public synchronized int capacity() {
	return value.length;
}

@Override
public synchronized void ensureCapacity(int minimumCapacity) {
	if (minimumCapacity > value.length) {
		expandCapacity(minimumCapacity);
	}
}

@Override
public synchronized void trimToSize() {
	super.trimToSize();
}

@Override
public synchronized void setLength(int newLength) {
	toStringCache = null;
	super.setLength(newLength);
}


@Override
public synchronized char charAt(int index) {
	if ((index < 0) || (index >= count))
		throw new StringIndexOutOfBoundsException(index);
	return value[index];
}

@Override
public synchronized int codePointAt(int index) {
	return super.codePointAt(index);
}
..... and rest of methods...

Why StringBuffer is thread safe?

The synchronized keyword differentiate the StringBuffer class from StringBuilder class, As we are aware synchronized keyword protects concurrent modification from multiple threads (i.e. at given point of time one and only one thread will enter StringBuffer and modified the data members of StringBuffer). Hence, StringBuffer class is thread safe class. “There is no such thing as a free lunch”, We are achieving the thread safely at the cost of performance.

Summarize StringBuffer & StringBuilder

Table: StringBuilder vs StringBuffer
S. No.StringBuilder StringBuffer
1StringBuilder is not thread safe, the methods of StringBuilder class are not synchronized StringBuffer is thread safe class, the methods of StringBuffer class are synchronized
2StringBuilder is more efficient than StringBuffer StringBuffer is less efficient than StringBuilder

Program – Join strings using StringBuilder & StringBuffer.

package org.learn;

public class StringBufferAndBuilder {

	public static void main(String[] args) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("Test");
		buffer.append("StringBuffer");
		//Output: StringBuffer
		System.out.println("1. Join strings using StringBuffer = " + buffer.toString());
		
		StringBuilder builder = new StringBuilder();
		builder.append("Test");
		builder.append("StringBuilder");
		//Output: StringBuilder
		System.out.println("2. Join strings using StringBuilder = " + builder.toString());
		System.out.println("3. Execution time of StringBuilder and StringBuffer");
		calculateTime();
	}
	
	private static void calculateTime() {
		long loopLimit = 500;
		
		long startBuilderTime = System.nanoTime();
		StringBuilder builder = new StringBuilder("Test");
		for (int index = 0; index < loopLimit; index++) {
			builder.append("ExecutingTime");
		}
		long builderExeTime = System.nanoTime() - startBuilderTime;
		System.out.printf("3.1 StringBuilder execution time = %d ns \n",builderExeTime);
		
		long startBufferTime = System.nanoTime();
		StringBuffer buffer = new StringBuffer("Test");
		for (int index = 0; index < loopLimit; index++) {
			buffer.append("ExecutingTime");
		}
		long bufferExeTime = System.nanoTime() - startBufferTime;
		System.out.printf("3.2 StringBuffer execution time  = %d ns\n",bufferExeTime);
		long timeDiff = bufferExeTime - builderExeTime;
		System.out.printf("3.3 Time StringBuffer-StringBuilder = %d ns",timeDiff);
	}
}

Output- concatenate strings using StringBuilder & StringBuffer

1. Join strings using StringBuffer = TestStringBuffer
2. Join strings using StringBuilder = TestStringBuilder
3. Execution time of StringBuilder and StringBuffer
3.1 StringBuilder execution time = 79406 ns 
3.2 StringBuffer execution time  = 204725 ns
3.3 Time StringBuffer-StringBuilder = 125319 ns
Exit mobile version