Posted In: Java Core, String

String vs StringBuilder vs StringBuffer Simple Benchmark test

Since String is immutable in java any changes to it creates a new object. StringBuffer and StringBuilder are mutable objects. They provide methods like append(), insert(), delete() and substring() to manipulate date.

 

This test clearly shows that always use StringBuilder. It will perform much better than String concatenation.

package com.example.java.core;

public class StringVsStringBuilder {
	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		System.out.println("start at=" + start);

		new StringVsStringBuilder().concanateString();
		System.out.println("string concanate time taken="
		        + (System.currentTimeMillis() - start));
		start = System.currentTimeMillis();

		new StringVsStringBuilder().concanateStringBuilder();
		System.out.println("stringbuilder concanate time taken="
		        + (System.currentTimeMillis() - start));
		start = System.currentTimeMillis();

		new StringVsStringBuilder().concanateStringBuffer();
		System.out.println("stringbuffer concanate time taken="
		        + (System.currentTimeMillis() - start));
	}

	public String concanateStringBuilder() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 100000; i++) {
			sb.append(i);
		}
		return sb.toString();
	}

	public String concanateStringBuffer() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 100000; i++) {
			sb.append(i);
		}
		return sb.toString();
	}

	public String concanateString() {
		String s = "";
		for (int i = 0; i < 100000; i++) {
			s += i;
		}
		return s;
	}
}

Result

start at=1503557385613
string concanate time taken=27590
stringbuilder concanate time taken=12
stringbuffer concanate time taken=14

by , on August 24th, 2017

  • Categories