Skip to content

Instantly share code, notes, and snippets.

@ewized
Created November 22, 2015 17:24
Show Gist options
  • Save ewized/0034888fbbfc77eb9834 to your computer and use it in GitHub Desktop.
Save ewized/0034888fbbfc77eb9834 to your computer and use it in GitHub Desktop.
Testing the performance hit of using different methods of running code.
import java.util.*;
public class Perm {
public static void main(String[] args) throws Exception {
Perm perm = new Perm();
long start = System.currentTimeMillis();
for (int i = 0; i < Integer.MAX_VALUE; i ++) {
perm.run();
}
System.out.println("Normal method: " + (System.currentTimeMillis() - start) + "ms");
perm = new Perm();
start = System.currentTimeMillis();
Run tmp = (Run) Perm.class.getField("onRun").get(perm);
for (int i = 0; i < Integer.MAX_VALUE; i ++) {
tmp.run();
}
System.out.println("Interface field: " + (System.currentTimeMillis() - start) + "ms");
Runner runner = new Runner();
start = System.currentTimeMillis();
for (int i = 0; i < Short.MAX_VALUE; i ++) {
Runner.class.getMethod("run").invoke(runner);
}
System.out.println("Reflection invoke: " + (System.currentTimeMillis() - start) + "ms");
}
public Run onRun = () -> { int i = 0; };
public void run() {
int i = 0;
}
static interface Run {
void run();
}
static class Runner implements Run {
@Override
public void run() {
int i = 0;
}
}
}

Normal method: 8ms
Interface field: 11ms
Reflection invoke: 85ms


Normal method: 8ms
Interface field: 10ms
Reflection invoke: 82ms


Normal method: 9ms
Interface field: 10ms
Reflection invoke: 84ms


Average normal method: 8.333ms
Average interface field: 10.333ms
Average reflection invoke: 83.666ms

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