Skip to content

Instantly share code, notes, and snippets.

@trasa
Created August 12, 2019 23:58
Show Gist options
  • Save trasa/9667cb69b5f7c975f23e619ea5559ac4 to your computer and use it in GitHub Desktop.
Save trasa/9667cb69b5f7c975f23e619ea5559ac4 to your computer and use it in GitHub Desktop.
how bad are exceptions vs performance in a tight loop, really? especially with modern JVMs...

Turns out the results are quite bad:

$ time java ThrowCounter ex
throw test
count is 5000000

real	0m3.243s
user	0m3.197s
sys	0m0.081s

$ time java ThrowCounter
boolean test
count is 5000000

real	0m0.136s
user	0m0.101s
sys	0m0.035s
public class ThrowCounter {
public static void main(String[] args) {
if (args.length == 0 || args[0].equalsIgnoreCase("bool")) {
runBooleanTest();
} else {
runThrowTest();
}
}
private static void runBooleanTest() {
System.out.println("boolean test");
int counter = 0;
for (int i=0; i < 10_000_000; i++) {
if (checkEven(i)) {
counter++;
}
}
System.out.println("count is " + counter);
}
private static boolean checkEven(int i) {
return i % 2 == 0;
}
private static void runThrowTest() {
System.out.println("throw test");
int counter = 0;
for(int i=0; i < 10_000_000; i++) {
try {
checkEvenException(i);
} catch (Exception e) {
counter++;
}
}
System.out.println("count is " + counter);
}
private static void checkEvenException(int i) throws Exception {
if (i % 2 == 0) {
throw new Exception("even!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment