本来是由于某个问题想用反射来解决,使用前作个小测试(我的应用都是用JDK1.4.2)。然后顺便把1.5的也测了。看到这个数据,不禁想到Hibernate,Spring这类依赖反射的框架是否更加适合运行在JDK1.4平台上。
补:后来在1.6上测了测,性能提高了不少,1.6真的是值得期待
Java 1.5
Reflection | Normal
3685|210
3696|210
4086|211
3685|211
3775|210
3696|210
Java 1.4.2Reflection | Normal
3295|340
3325|370
3295|340
3315|350
3305|340
3285|330
Java 1.6 beta2
Reflection | Normal
2954|200
2644|581
3005|170
2944|190
2684|170
3014|191
测试代码
1 import java.lang.reflect.*;
2
3 class ReflectTest {
4
5 public static void main(String[] args) {
6 String firstWord = "Hello ";
7 String secondWord = "everybody.";
8
9 for (int i=0; i<100000; i++) {
10 String bothWords = append2(firstWord, secondWord);
11 }
12 for (int i=0; i<100000; i++) {
13 String bothWords = append(firstWord, secondWord);
14 }
15
16 long begin = System.currentTimeMillis();
17 for (int i=0; i<1000000; i++) {
18 String bothWords = append(firstWord, secondWord);
19 }
20 System.out.println("Reflection:" + (System.currentTimeMillis() - begin));
21
22 begin = System.currentTimeMillis();
23 for (int i=0; i<1000000; i++) {
24 String bothWords = append2(firstWord, secondWord);
25 }
26 System.out.println("Normal:" + (System.currentTimeMillis() - begin));
27
28 }
29
30 public static String append(String firstWord, String secondWord) {
31 String result = null;
32 Class c = String.class;
33 Class[] parameterTypes = new Class[] {String.class};
34 Method concatMethod;
35 Object[] arguments = new Object[] {secondWord};
36 try {
37 concatMethod = c.getMethod("concat", parameterTypes);
38 result = (String) concatMethod.invoke(firstWord, arguments);
39 }
40 catch (NoSuchMethodException e) {
41 System.out.println(e);
42 }
43 catch (IllegalAccessException e) {
44 System.out.println(e);
45 }
46 catch (InvocationTargetException e) {
47 System.out.println(e);
48 }
49 return result;
50 }
51
52 public static String append2(String firstWord, String secondWord) {
53 return firstWord.concat(secondWord);
54 }
55 }