Skip to content

Instantly share code, notes, and snippets.

@lowasser
Created March 18, 2012 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lowasser/2071935 to your computer and use it in GitHub Desktop.
Save lowasser/2071935 to your computer and use it in GitHub Desktop.
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