1 17 18 package org.sape.carbon.core.test; 19 20 import java.lang.reflect.InvocationHandler ; 21 import java.lang.reflect.Method ; 22 import java.lang.reflect.Proxy ; 23 24 28 public class DynamicProxyPerformance { 29 30 public static void main(String [] args) throws ClassNotFoundException { 31 32 Something mySomething = new DynamicProxyPerformance.IH(); 33 34 Something myDynamicSomething = 35 (Something) 36 Proxy.newProxyInstance( 37 Something.class.getClassLoader(), 38 new Class [] {Something.class}, 39 (InvocationHandler ) mySomething); 40 41 final int ITERATIONS = 10000000; 42 System.out.println("Testing " + ITERATIONS + " iterations"); 43 44 45 long start = System.currentTimeMillis(); 46 for (int i = 0; i < ITERATIONS; i++) { 47 mySomething.doSomething(); 48 } 49 long time1 = (System.currentTimeMillis() - start); 50 System.out.println("Static finished at " + mySomething + " in: " + time1 + "ms"); 51 52 53 54 start = System.currentTimeMillis(); 55 for (int i = 0; i < ITERATIONS; i++) { 56 myDynamicSomething.doSomething(); 57 } 58 long time2 = (System.currentTimeMillis() - start); 59 System.out.println("Dynamic finished at " + mySomething + " in: " + time2 + "ms"); 60 System.out.println("Speed of 1 is " + ((((double) time2))/((double) time1)*100D) + "% of 2"); 61 62 63 64 Method m = null; 65 try { 66 m = mySomething.getClass().getMethod("doSomething",new Class [] {}); 67 } catch (Exception e) { } 68 69 start = System.currentTimeMillis(); 70 try { 71 for (int i = 0; i < ITERATIONS; i++) { 72 m.invoke(mySomething,new Object [] { }); 73 } 74 } catch (Exception e) { } 75 76 long time3 = (System.currentTimeMillis() - start); 77 System.out.println("Reflection finished at " + mySomething + " in: " + time3 + "ms"); 78 System.out.println("Speed of 2 is " + ((((double) time3))/((double) time2)*100D) + "% of 3"); 79 } 80 81 public static interface Something { 82 void doSomething(); 83 } 84 85 86 public static class IH implements InvocationHandler ,Something { 87 private Method theMethod = null; 88 public Object invoke(Object obj, Method method, Object [] obj2) 89 throws java.lang.Throwable { 90 91 92 93 if (theMethod == null) 94 theMethod = method; 95 96 if (method == theMethod) { 98 doSomething(); 99 } 100 return null; 101 } 102 103 public int x = 0; 104 public void doSomething() { 105 ++x; 106 } 107 108 public String toString() { 109 return "(" + x + ")"; 110 } 111 } 112 } | Popular Tags |