Skip to content

Instantly share code, notes, and snippets.

@ddrone
Created August 27, 2013 19:35
Show Gist options
  • Select an option

  • Save ddrone/6358003 to your computer and use it in GitHub Desktop.

Select an option

Save ddrone/6358003 to your computer and use it in GitHub Desktop.
import org.openjdk.jmh.annotations.GenerateMicroBenchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ProxyTest {
private static interface CatInterface {
public CatInterface computeSine();
}
private static class Cat implements CatInterface {
public final String name;
private final double argument;
private double sine, cosine;
private Cat(String name, double argument) {
this.name = name;
this.argument = argument;
}
public Cat computeSine() {
this.sine = Math.sin(argument);
this.cosine = Math.cos(argument);
return this;
}
}
@State(Scope.Benchmark)
public static class BenchmarkState {
List<CatInterface> cats = Arrays.<CatInterface>asList(new Cat("Felix", 1.0), new Cat("Tiger", 2.0), new Cat("Tom", 3.0));
}
@GenerateMicroBenchmark
public List<CatInterface> forLoopCats(BenchmarkState state) {
List<CatInterface> result = new ArrayList<CatInterface>();
for (final CatInterface cat : state.cats) {
result.add(cat.computeSine());
}
return result;
}
@GenerateMicroBenchmark
public CatInterface proxyForeachTest(BenchmarkState state) {
return forEach(CatInterface.class, state.cats).computeSine();
}
@SuppressWarnings("unchecked")
public static <T> T forEach(Class<T> clazz, Collection<T> collection) {
T proxy = (T) Proxy.newProxyInstance(
ForEachInvocationHandler.class.getClassLoader(),
new Class[] { clazz },
new ForEachInvocationHandler<T>(clazz, collection)
);
return proxy;
}
private static class ForEachInvocationHandler<T> implements InvocationHandler {
private final Collection<T> collection;
private final Class<T> clazz;
private ForEachInvocationHandler(Class<T> clazz, Collection<T> collection) {
this.collection = collection;
this.clazz = clazz;
}
@Override
@SuppressWarnings("all")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
List result = new ArrayList();
for (T elem : collection) {
result.add(method.invoke(elem, args));
}
return forEach(clazz, result);
}
}
}
Benchmark Mode Thr Cnt Sec Mean Mean error Units
o.o.j.b.ProxyTest.forLoopCats thrpt 4 10 1 3723.030 236.622 ops/msec
o.o.j.b.ProxyTest.proxyForeachTest thrpt 4 10 1 234.002 14.928 ops/msec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment