Friday, July 11, 2014

StringBuffer Vs StringBuilder

The below example provides the performance comparision between StringBuffer & StringBuilder class.


public class StringBufferVsStringBuilder {

  static String dontOptimiseAway = null;
  static String[] words = new String[100000];

  public static void main(String... args) {
    for (int i = 0; i < words.length; i++)
      words[i] = Integer.toString(i);

    for (int i = 0; i < 10; i++) {
      dontOptimiseAway = testStringBuffer();
      dontOptimiseAway = testStringBuilder();
    }

  }

  private static String testStringBuffer() {
    long start = System.nanoTime();
    StringBuffer sb = new StringBuffer();

    for (String word : words) {
      sb.append(word).append(',');
    }

    String s = sb.substring(0, sb.length() - 1);
    long time = System.nanoTime() - start;
    System.out.printf("StringBuffer: took %d ns per word%n", time / words.length);
    return s;

  }

  private static String testStringBuilder() {
    long start = System.nanoTime();
    StringBuilder sb = new StringBuilder();

    for (String word : words) {
      sb.append(word).append(',');
    }

    String s = sb.substring(0, sb.length() - 1);
    long time = System.nanoTime() - start;
    System.out.printf("StringBuilder: took %d ns per word%n", time / words.length);
    return s;
  }

}

OUTPUT

StringBuffer: took 214 ns per word
StringBuilder: took 273 ns per word
StringBuffer: took 199 ns per word
StringBuilder: took 71 ns per word
StringBuffer: took 3740 ns per word
StringBuilder: took 134 ns per word
StringBuffer: took 134 ns per word
StringBuilder: took 61 ns per word
StringBuffer: took 250 ns per word
StringBuilder: took 52 ns per word
StringBuffer: took 65 ns per word
StringBuilder: took 35 ns per word
StringBuffer: took 188 ns per word
StringBuilder: took 43 ns per word
StringBuffer: took 64 ns per word
StringBuilder: took 36 ns per word
StringBuffer: took 213 ns per word
StringBuilder: took 50 ns per word
StringBuffer: took 69 ns per word
StringBuilder: took 38 ns per word

No comments :

Post a Comment