Pages

Friday, December 31, 2010

Plus empty string - not the best way to ensure not nullness

In continuation of the previous post yet another silly benchmark. On Topcoder and in the code at work I have seen such a construction variable (of type String) = variable + "" to ensure that the value is not null. as it leads to creation of the StringBuilder object it is obvious that it is not very optimal. But is just pure performance or a very-very pure performance? Here is a straightforward bench. If someone see why the part without plus should be faster because of some not related to the subject stuff - please leave a comment.

import java.util.Random;

public class PlusEmptyStringBench {
  private static Random r = new Random();

  public static void main(String[] args) {
    long nanoTime = System.nanoTime();
    for (int i = 0; i < 10000000; i++) {
      doWithCheck();
    }
    System.out.println("With check: " + (System.nanoTime() - nanoTime));
    nanoTime = System.nanoTime();
    for (int i = 0; i < 10000000; i++) {
      doWithPlus();
    }
    System.out.println("With plus: " + (System.nanoTime() - nanoTime));
  }

  private static String checkNotNull(String forCheck) {
    if (forCheck == null) {
      return "null";
    } else {
      return forCheck;
    }
  }

  private static void doWithPlus() {
    if (r.nextBoolean()) {
      String local = null + "";
    } else {
      String local = String.valueOf(r.nextBoolean()) + "";
    }
  }

  private static void doWithCheck() {
    if (r.nextBoolean()) {
      String local = checkNotNull(null);
    } else {
      String local = checkNotNull(String.valueOf(r.nextBoolean()));
    }
  }
}


* This source code was highlighted with Source Code Highlighter.


The output of this code is:

With check: 297321208
With plus: 922518553

No comments:

Post a Comment