Skip to content

Instantly share code, notes, and snippets.

@wangzaixiang
Created December 26, 2011 07:15
Show Gist options
  • Save wangzaixiang/1520686 to your computer and use it in GitHub Desktop.
Save wangzaixiang/1520686 to your computer and use it in GitHub Desktop.
Test Performance for MethodInvoker, Reflect
package demo.invoke;
import java.lang.invoke.*;
import java.lang.reflect.Method;
@SuppressWarnings("unused")
public class TestSimple {
public static final int LOOPS = 100000000;
public static void main(String[] args) throws Throwable {
testDirect();
testInvoker();
testReflect();
}
static void testReflect() throws Throwable {
String test = "Hello World";
long start = System.currentTimeMillis();
Method method = String.class.getMethod("replace", char.class, char.class);
for(int i = 0; i<LOOPS; i++){
// test.replace('o', 'O');
// System.out.println("Invoke " + i);
String res = (String) method.invoke(test, 'o', 'O');
}
long end = System.currentTimeMillis();
System.out.println("TestReflect Total time is " + (end-start));
}
static void testInvoker() throws Throwable{
String test = "Hello World";
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType methodType = MethodType.methodType(String.class, char.class, char.class);
MethodHandle mh = lookup.findVirtual(String.class, "replace", methodType);
long start = System.currentTimeMillis();
for(int i = 0; i<LOOPS; i++){
// test.replace('o', 'O');
// System.out.println("Invoke " + i);
String res = (String) mh.invoke(test, 'o', 'O');
}
long end = System.currentTimeMillis();
System.out.println("TestInvoke Total time is " + (end-start));
}
static void testDirect(){
String test = "Hello World";
long start = System.currentTimeMillis();
for(int i = 0; i<LOOPS; i++){
String str = test.replace('o', 'O');
}
long end = System.currentTimeMillis();
System.out.println("TestDirect Total time is " + (end-start));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment