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 test string :: ");
}
String resultStr = sb.toString();
long endTime = System.currentTimeMillis();
System.out.println("\tEnd time ="+endTime);
System.out.println("\tTotal time taken = "+ ((endTime - startTime)));
return endTime-startTime;
}
public static long usingStringBuilder(){
long startTime = System.currentTimeMillis();
System.out.println("\tStart time = "+ startTime);
StringBuilder sb = new StringBuilder();
for(int i=0;i<1000000;i++){
sb.append("\tSample test string :: ");
}
String resultStr = sb.toString();
long endTime = System.currentTimeMillis();
System.out.println("\tEnd time ="+endTime);
System.out.println("\tTotal time taken = "+ ((endTime - startTime)));
return endTime-startTime;
}
}
Here is the output
Using StringBuffer
Start time = 1321171861338
End time =1321171861909
Total time taken = 571
Using String Builder
Start time = 1321171861910
End time =1321171862393
Total time taken = 483
Improved in performance = 15.411558669001751%
Comments
Post a Comment