Skip to content

Instantly share code, notes, and snippets.

@andytill
Created November 2, 2012 10:11
Show Gist options
  • Select an option

  • Save andytill/3999932 to your computer and use it in GitHub Desktop.

Select an option

Save andytill/3999932 to your computer and use it in GitHub Desktop.
A benchmark for testing method handle performance.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodHandleTest
{
private static final String METHOD_NAME = "increment";
private static final int LOOPS = 1000000;
static class Incrementer
{
long incrementedNumber;
public void increment(String arg)
{
// just do something
incrementedNumber += 1;
}
}
public static void main(String[] args) throws Throwable
{
usingReflection();
usingMethodHandles();
}
private static void usingReflection() throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException
{
Method method = Incrementer.class.getMethod(METHOD_NAME, String.class);
long startTime = System.currentTimeMillis();
Incrementer increments = new Incrementer();
for (int i = 0; i < LOOPS; i++)
{
method.invoke(increments, "12345");
}
long elapsed = System.currentTimeMillis() - startTime;
System.out.println("reflection took " + elapsed + "ms, result is " + increments.incrementedNumber);
}
private static void usingMethodHandles() throws NoSuchMethodException,
IllegalAccessException, Throwable
{
MethodType methodType;
MethodHandle methodHandle;
MethodHandles.Lookup lookup = MethodHandles.lookup();
methodType = MethodType.methodType(void.class, String.class);
methodHandle = lookup.findVirtual(Incrementer.class, METHOD_NAME, methodType);
long startTime = System.currentTimeMillis();
Incrementer increments = new Incrementer();
for (int i = 0; i < LOOPS; i++)
{
methodHandle.invokeExact(increments, "12345");
}
long elapsed = System.currentTimeMillis() - startTime;
System.out.println("method handles took " + elapsed + "ms, result is " + increments.incrementedNumber);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment