Skip to content

Instantly share code, notes, and snippets.

@dyokomizo
Created March 24, 2012 16:07
Show Gist options
  • Save dyokomizo/2184649 to your computer and use it in GitHub Desktop.
Save dyokomizo/2184649 to your computer and use it in GitHub Desktop.
Reflection performance
package functional;
class Foo {
public String bar() {
if (System.currentTimeMillis() > 0) {return null;}
return "baz";
}
}
package functional;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Function;
public class FunctionBenchmark extends SimpleBenchmark {
final Foo foo = new Foo();
final Function<Foo, String> f = new Function<Foo, String>() {
@Override public String apply(Foo input) {
return input.bar();
}
};
public String timeCall(int n) {
String s = null;
for (int i = 0; i < n; i++) {
s = f.apply(foo);
}
return s;
}
}
package functional;
import com.google.caliper.SimpleBenchmark;
public class MethodCallBenchmark extends SimpleBenchmark {
final Foo foo = new Foo();
public String timeCall(int n) {
String s = null;
for (int i = 0; i < n; i++) {
s = foo.bar();
}
return s;
}
}
package functional;
import java.lang.reflect.Method;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Function;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ReflectionBenchmark extends SimpleBenchmark {
final Foo foo = new Foo();
final Function<Foo, String> f = new Function() {
final Method method;
{
try {
method = Foo.class.getMethod("bar");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override public Object apply(Object input) {
try {
return method.invoke(input);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
public String timeCall(int n) {
String s = null;
for (int i = 0; i < n; i++) {
s = f.apply(foo);
}
return s;
}
}
@dyokomizo
Copy link
Author

java -cp .:../lib/caliper-0.5-rc1.jar:../lib/guava-osgi-11.0.0.jar:../lib/gson-1.7.1.jar com.google.caliper.Runner functional.MethodCallBenchmark
0% Scenario{vm=java, trial=0, benchmark=Call} 146.04 ns; σ=0.79 ns @ 3 trials

java -cp .:../lib/caliper-0.5-rc1.jar:../lib/guava-osgi-11.0.0.jar:../lib/gson-1.7.1.jar com.google.caliper.Runner functional.FunctionBenchmark
0% Scenario{vm=java, trial=0, benchmark=Call} 145.67 ns; σ=0.14 ns @ 3 trials

java -cp .:../lib/caliper-0.5-rc1.jar:../lib/guava-osgi-11.0.0.jar:../lib/gson-1.7.1.jar com.google.caliper.Runner functional.ReflectionBenchmark
0% Scenario{vm=java, trial=0, benchmark=Call} 161.13 ns; σ=5.71 ns @ 10 trials

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment