Posts

Showing posts with the label StringBuilder

StringBuffer vs StringBuilder : Performance improvement figures

IN previous post StringBuffer vs StringBuilder , I have explained benefits of using StringBuilder over StringBuffer. Here are some performance figure using both for concatenating string. package com.test;   public class StringConcatenateTest { public static void main(String[] args) { System.out.println( "Using StringBuffer" ); long bufferTime = usingStringBuffer(); System.out.println( "Using String Builder" ); long builderTime = usingStringBuilder(); double perc = (( double )(bufferTime-builderTime)/bufferTime)* 100; System.out.println( "Improved in performance = " + perc + "%" ); } public static long usingStringBuffer(){ long startTime = System.currentTimeMillis(); System.out.println( "\tStart time = " + startTime); StringBuffer sb = new StringBuffer(); for ( int i=0;i<1000000;i++){ sb.append( "\tSample ...

StringBuilder over StringBuffer

As String is an immutable class , any update operations  like replace/substring/append is very expensive. As solution for this StringBuffer class has been introduced for all string update related operations. But problem with StringBuffer is that it is a synchronized class. All its public methods are tagged as “synchronized”. This adds an extra cost to string update operation whenever synchronized is actually not needed. As part of JDK 1.5 a new utility class called StringBuilder has been introduced for non-synchronized string update operations. StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. It means using StrinBuilder instead of StringBuffer where ever synchronization is not an issue will be added to program performance.