1 16 package net.sf.cglib.reflect; 17 18 import java.lang.reflect.Constructor ; 19 import java.lang.reflect.Method ; 20 import java.util.*; 21 import junit.framework.*; 22 23 public class TestReflectPerf extends net.sf.cglib.CodeGenTestCase { 24 public interface IndexOf { 25 int indexOf(String s, int start); 26 } 27 28 public void testReflectPerf() throws Throwable { 29 int iterations = 1000000; 30 System.out.println(); 31 System.out.println("iteration count: " + iterations); 32 33 String test = "abcabcabc"; 34 35 Class [] types = new Class []{ String .class, Integer.TYPE }; 36 Method indexOf = String .class.getDeclaredMethod("indexOf", types); 37 FastClass fc = FastClass.create(String .class); 38 FastMethod fm = fc.getMethod("indexOf", types); 39 int fidx = fm.getIndex(); 40 Object [] args = new Object []{ "ab", new Integer (1) }; 41 42 IndexOf fast = (IndexOf)MethodDelegate.create(test, "indexOf", IndexOf.class); 43 44 int result; 45 long t1 = System.currentTimeMillis(); 46 for (int i = 0; i < iterations; i++) { 47 result = ((Integer )fc.invoke("indexOf", types, test, args)).intValue(); 48 } 49 long t2 = System.currentTimeMillis(); 50 for (int i = 0; i < iterations; i++) { 51 args = new Object []{ "ab", new Integer (1) }; 52 result = ((Integer )indexOf.invoke(test, args)).intValue(); 53 } 54 long t3 = System.currentTimeMillis(); 55 for (int i = 0; i < iterations; i++) { 56 result = ((Integer )indexOf.invoke(test, args)).intValue(); 57 } 58 long t4 = System.currentTimeMillis(); 59 for (int i = 0; i < iterations; i++) { 60 args = new Object []{ "ab", new Integer (1) }; 61 result = ((Integer )fm.invoke(test, args)).intValue(); 62 } 63 long t5 = System.currentTimeMillis(); 64 for (int i = 0; i < iterations; i++) { 65 result = ((Integer )fm.invoke(test, args)).intValue(); 66 } 67 long t6 = System.currentTimeMillis(); 68 for (int i = 0; i < iterations; i++) { 69 result = ((Integer )fc.invoke(fidx, test, args)).intValue(); 70 } 71 long t7 = System.currentTimeMillis(); 72 for (int i = 0; i < iterations; i++) { 73 result = fast.indexOf("ab", 1); 74 } 75 long t8 = System.currentTimeMillis(); 76 for (int i = 0; i < iterations; i++) { 77 result = test.indexOf("ab", 1); 78 } 79 long t9 = System.currentTimeMillis(); 80 81 System.out.println("fc = " + (t2 - t1) 82 + "\n" + "reflect+args = " + (t3 - t2) 83 + "\n" + "reflect = " + (t4 - t3) 84 + "\n" + "fm+args = " + (t5 - t4) 85 + "\n" + "fm = " + (t6 - t5) 86 + "\n" + "fc w/idx = " + (t7 - t6) 87 + "\n" + "delegate = " + (t8 - t7) 88 + "\n" + "raw = " + (t9 - t8)); 89 } 90 91 92 93 public TestReflectPerf(String testName) { 94 super(testName); 95 } 96 97 public static void main(String [] args) { 98 junit.textui.TestRunner.run(suite()); 99 } 100 101 public static Test suite() { 102 return new TestSuite(TestReflectPerf.class); 103 } 104 105 public void perform(ClassLoader loader) throws Throwable { 106 } 107 108 public void testFailOnMemoryLeak() throws Throwable { 109 } 110 111 } 112 | Popular Tags |