Created
November 2, 2012 10:11
-
-
Save andytill/3999932 to your computer and use it in GitHub Desktop.
A benchmark for testing method handle performance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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