0%

java | 性能检测与提高

简单的检测和提高。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.redisc;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Person {
public String getName() {
return name;
}

public String getName2() {
return name2;
}

public void setName(String name) {
this.name = name;
}

public String name;
private String name2;

public Person(String name) {
this.name = name;
}

public Person() {
}
}


public class Test {


public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
// 普通方法调用
Person person = new Person();
long statrTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
person.getName();
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - statrTime);

// 反射方法调用

Person person2 = new Person();
Class c1 = person2.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long statrTime2 = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(person2, null);
}
long endTime2 = System.currentTimeMillis();
System.out.println(endTime2 - statrTime2);


// 反射方法验证关闭
// 反射方法调用
Person person3 = new Person();
Class c3 = person3.getClass();
Method getName3 = c3.getDeclaredMethod("getName", null);
getName3.setAccessible(true);
long statrTime3 = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName3.invoke(person3, null);
}
long endTime3 = System.currentTimeMillis();
System.out.println(endTime3 - statrTime3);

}
}

输出

1
2
3
5
3364
1510
请我喝杯咖啡吧~