Skip to content

Instantly share code, notes, and snippets.

@volgar1x
Created March 14, 2014 15:21
Show Gist options
  • Save volgar1x/9549840 to your computer and use it in GitHub Desktop.
Save volgar1x/9549840 to your computer and use it in GitHub Desktop.
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class MethodHandlePerfs {
public static interface Task {
void run(int N) throws Throwable;
}
public static double addFive(double d) {
return d + 5.0;
}
public static Duration time(int iterations, Task task) {
try {
long start = System.nanoTime();
task.run(iterations);
long end = System.nanoTime();
return Duration.of(end - start, ChronoUnit.NANOS).dividedBy(iterations);
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static void bench(int iterations, String name, Task task) {
Duration d = time(iterations, task);
System.out.printf("%12s = %-3dns\n", name, d.toNanos());
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(double.class, double.class);
MethodHandle handle = lookup.findStatic(MethodHandlePerfs.class, "addFive", mt);
Method method = MethodHandlePerfs.class.getMethod("addFive", double.class);
bench(1_000_000_000, "invokeExact" , N -> {
for (int i = 0; i < N; i++) {
@SuppressWarnings("UnusedDeclaration")
double ignored = (double) handle.invokeExact(5.0);
}
});
bench(1_000_000_000, "invoke", N -> {
for (int i = 0; i < N; i++) {
@SuppressWarnings("UnusedDeclaration")
double ignored = (double) handle.invoke(5.0);
}
});
bench(1_000_000_000, "reflection", N -> {
for (int i = 0; i < N; i++) {
method.invoke(null, 5.0);
}
});
bench(1_000_000_000, "static", N -> {
for (int i = 0; i < N; i++) {
@SuppressWarnings("UnusedDeclaration")
double ignored = addFive(5.0);
}
});
}
}
invokeExact = 11 ns
invoke = 11 ns
reflection = 6 ns
static = 0 ns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment