Pages

Wednesday, November 24, 2010

Specifying the size for StringBuilder

Curiously in C# simple string concatenation is faster in some cases than using the StringBuilder class. As far as I understand from the documentation and surfing the net it is not possible in Java as any string concatenation there is substituted by the StringBuilder usage. Here is a little benchmark to measure the difference in using the simple StringBuilder constructor and the constructor with the predefined proper maximum size. It is very rough as it is not even using something other than ints.

  public static void main(String[] args) {
    final int benchScale = 10;
    long[] slowTimes = new long[benchScale];
    for (int i = 0; i < benchScale; i++) {
      slowTimes[i] = slow();
    }
    long[] fastTimes = new long[benchScale];
    for (int i = 0; i < benchScale; i++) {
      fastTimes[i] = fast();
    }

    long slowAv = 0L;
    for (long i : slowTimes) {
      slowAv += i;
    }
    slowAv /= slowTimes.length;

    long fastAv = 0L;
    for (long i : fastTimes) {
      fastAv += i;
    }
    fastAv /= fastTimes.length;

    System.out.println("slow average " + slowAv);
    System.out.println("fast average " + fastAv);
  }

  private static long fast() {
    long now = System.currentTimeMillis();
    StringBuilder s = new StringBuilder(100000);
    for (int i = 0; i < 100000; i++) {
      s.append("*");
    }
    return System.currentTimeMillis() - now;
  }

  private static long slow() {
    long now = System.currentTimeMillis();
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < 100000; i++) {
      s.append("*");
    }
    return System.currentTimeMillis() - now;
  }


* This source code was highlighted with Source Code Highlighter.

The output of this code may vary, but usually it is something like this:

slow average 3
fast average 2

Interestingly, if benchScale local variable is bumped to 100 or higher the output almost always will be this:

slow average 1
fast average 1

No comments:

Post a Comment