Skip to content

Instantly share code, notes, and snippets.

@adaptives
Created July 26, 2011 10:38
Show Gist options
  • Save adaptives/1106467 to your computer and use it in GitHub Desktop.
Save adaptives/1106467 to your computer and use it in GitHub Desktop.
StringBuffer and StringBuilder
package com.diycomputerscience;
public class StringBufferAndBuilder {
public static final int MAX_ITER = 10000;
/**
* @param args
* This example shows how to perform common String operations in Java
*/
public static void main(String[] args) {
//We will concatenate Strings in three different ways, in the
//methods below
long t1 = concatenateWithPlusOperator();
long t2 = concatenateWithStringBuffer();
long t3 = concatenateWithStringBuilder();
//All of the above ways of concatenating have performance
//implications. Let us see the difference in performance.
//Using StringBuffer is faster than using the '+' operator
System.out.println("ConcatenateWithStringBuffer is " +
(double)t1/(double)t2 +
" times faster than Concatanate");
//Using StringBuilder is faster than using StringBuffer
System.out.println("ConcatanateWithStringBuilder is " +
(double)t2/(double)t3 +
" times faster than ConcatanateWithStringBuffer");
}
private static long concatenateWithPlusOperator() {
String s1 = "";
long s1Time = getNanoTime();
for(int i=0;i<MAX_ITER;i++) {
s1 = s1 + "abc";
}
long e1Time = getNanoTime();
System.out.println("Time taken to concatenate using '+' : " +
(e1Time - s1Time) + " nanoseconds");
return e1Time - s1Time;
}
private static long concatenateWithStringBuffer() {
StringBuffer sb = new StringBuffer();
long s2Time = getNanoTime();
for(int i=0;i<MAX_ITER;i++) {
sb.append("abc");
}
long e2Time = getNanoTime();
System.out.println("Time taken to concatenate using StringBuffer: " +
(e2Time - s2Time) + " nanoseconds");
return e2Time - s2Time;
}
private static long concatenateWithStringBuilder() {
StringBuilder sBuilder = new StringBuilder();
long s3Time = getNanoTime();
for(int i=0;i<MAX_ITER;i++) {
sBuilder.append("abc");
}
long e3Time = getNanoTime();
System.out.println("Time taken to concatenate using StringBuilder: : " +
(e3Time - s3Time) + " nanoseconds");
return e3Time - s3Time;
}
private static long getNanoTime() {
return System.nanoTime();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment