I have been trying to understand the difference between using new
to instantiate an object vs using Class.forName("A").newInstance();
.
I have run the following code for a simple class A
which shows using Class.forname("A").newInstance()
is 70-100 times slower than using just new A()
.
I am curious to know why there is such a difference in time, but couldn't figure out. Please someone help me to understand the reason.
public class Main4test {
public Main4test() {
}
static int turns = 9999999;
public static void main(String[] args) {
new Main4test().run();
}
public void run() {
System.out.println("method1: " + method1() + "");
System.out.println("method2:" + method2() + "");
}
public long method2() {
long t = System.currentTimeMillis();
for (int i = 0; i < turns; i++) {
try {
A a = (A) Class.forName("A").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return System.currentTimeMillis() - t;
}
public long method1() {
long t = System.currentTimeMillis();
for (int i = 0; i < turns; i++) {
try {
A a = new A();
} catch (Exception e) {
e.printStackTrace();
}
}
return System.currentTimeMillis() - t;
}
}
public class A {
int a;
public A() {
a=0;
}
}