Laliluna Sebastian Hennebrüder

Performance of Java exceptions

Influence of exception on the application performance.

Influence of exception on the application performance The first converter uses exceptions to determine if a value is not a Long value.

try {
  value = Long.parseLong(toParse.trim());
} catch (NumberFormatException e) {
  isLong = false;
}

The second example evaluates if the String contains of digits only.

  char buf[] = toParse.trim().toCharArray();

  for (char c : buf) {
    if (!Character.isDigit(c))
      isLong = false;
    }

    if (isLong) {
      value = Long.parseLong(toParse);
    }

With a String of “123456a” the second approach is more than 10 times faster. A shorter parse string requires even less time.

It is important to know that the time needed per thousand runs is only 2 milliseconds for the exception version. In most cases this should play no importance.

Kind Regards / Viele Grüße

Sebastian Hennebrueder