8

java | 性能检测与提高

 1 year ago
source link: https://benpaodewoniu.github.io/2022/12/11/java74/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java | 性能检测与提高

2022-12-11java进阶反射

1

简单的检测和提高。

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);

}
}
5
3364
1510

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK