主要对比三种创建对象的方法.
- 直接new
- .class
- Class.forName
- 采用纳秒对比,毫秒对比结果是0.可见,创建一个对象的耗时,是纳秒级别.
- 环境是OpenJDK Runtime Environment AdoptOpenJDK (build 14+36)
结果: 直接new最快, Class.forName次之, .class方式最慢
new nanoTime:4600
userObj1:{"User":{"id":null,"name":"null"}}
.class nanoTime:84700
userObj2:{"User":{"id":null,"name":"null"}}
Class.forName nanoTime:22200
userObj3:{"User":{"id":null,"name":"null"}}
源码如下
import java.lang.reflect.InvocationTargetException;
/**
* 测试用User
*
* @author ming san
* @since 2020-07-22 21:32:11
*/
public class User {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
long timeStart1 = System.nanoTime();
User userObj1 = new User();
System.out.println("new nanoTime:" + (System.nanoTime() - timeStart1));
System.out.println("userObj1:" + userObj1);
System.out.println();
long timeStart2 = System.nanoTime();
Class<User> userClass2 = User.class;
User userObj2 = userClass2.getDeclaredConstructor().newInstance();
System.out.println(".class nanoTime:" + (System.nanoTime() - timeStart2));
System.out.println("userObj2:" + userObj2);
System.out.println();
long timeStart3 = System.nanoTime();
Class<?> userClass3 = Class.forName("com.mingsan.User");
User userObj3 = (User) userClass3.getDeclaredConstructor().newInstance();
System.out.println("Class.forName nanoTime:" + (System.nanoTime() - timeStart3));
System.out.println("userObj3:" + userObj3);
}
private Integer id;
private String name;
public User() {
}
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "{\"User\":{"
+ "\"id\":"
+ id
+ ",\"name\":\""
+ name + '\"'
+ "}}";
}
}
网友评论