3 回答

TA貢獻1780條經驗 獲得超4個贊
是的-當然。
由于反射涉及動態(tài)解析的類型,因此無法執(zhí)行某些Java虛擬機優(yōu)化。因此,反射操作的性能比它們的非反射操作要慢,在性能敏感的應用程序中經常調用的代碼部分應該避免反射操作。
public class Main { public static void main(String[] args) throws Exception { doRegular(); doReflection(); } public static void doRegular() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = new A(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); } public static void doReflection() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = (A) Class.forName("misc.A").newInstance(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); }}
35 // no reflection465 // using reflection
30 // no reflection47 // reflection using one lookup, only instantiating

TA貢獻1802條經驗 獲得超5個贊

TA貢獻1846條經驗 獲得超7個贊
new A(), 141 ns A.class.newInstance(), 266 nsnew A(), 103 ns A.class.newInstance(), 261 nspublic class Run { private static final int RUNS = 3000000; public static class A { } public static void main(String[] args) throws Exception { doRegular(); doReflection(); doRegular(); doReflection(); } public static void doRegular() throws Exception { A[] as = new A[RUNS]; long start = System.nanoTime(); for (int i = 0; i < RUNS; i++) { as[i] = new A(); } System.out.printf("new A(), %,d ns%n", (System.nanoTime() - start)/RUNS); } public static void doReflection() throws Exception { A[] as = new A[RUNS]; long start = System.nanoTime(); for (int i = 0; i < RUNS; i++) { as[i] = A.class.newInstance(); } System.out.printf("A.class.newInstance(), %,d ns%n", (System.nanoTime() - start)/RUNS); }}
添加回答
舉報