Create a gist now

Instantly share code, notes, and snippets.

package com.google.common.collect;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.Random;
public class NullCheck extends SimpleBenchmark {
Object[] array = new Object[0x10000];
@Override
protected void setUp() throws Exception {
Random rng = new Random();
for (int i = 0; i < 0x10000; i++) {
array[i] = rng.nextBoolean() ? new Object() : null;
}
}
public int timeIfCheck(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
Object o = array[i & 0xffff];
if (o != null) {
tmp += o.hashCode();
}
}
return tmp;
}
public int timeTryCatch(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
try {
tmp += array[i & 0xffff].hashCode();
} catch (NullPointerException e) {
}
}
return tmp;
}
public static void main(String[] args) {
Runner.main(NullCheck.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment