调用newInstance()是否有代价,或者它的底层机制是相同的吗?newInstance()在新关键字*上有多少开销?
*:忽略newInstance()暗示使用反射的事实。
发布于 2009-03-15 03:17:17
在真实世界的测试中,通过"Constuctor.newInstance“传递10个参数来创建一个类的18129个实例-而不是通过"new”创建实例-程序在时间上没有可测量的差异。
这不是任何类型的微基准测试。
这是Windows7 x86测试版上的JDK 1.6.0_12。
鉴于Constructor.newInstance将非常类似于Class.forName.newInstance,我想说,考虑到您可以使用newInstance而不是new获得的功能,开销几乎是微不足道的。
像往常一样,你应该自己测试一下。
发布于 2009-03-15 02:19:22
要小心微基准测试,但我发现了this blog entry,在那里有人发现使用JDK1.4时,new
的速度大约是newInstance
的两倍。这听起来是有区别的,而且正如预期的那样,反射速度更慢。然而,听起来这种差异可能不会破坏交易,这取决于新对象实例的频率与正在完成的计算量。
发布于 2013-08-31 05:15:46
这是不同的-在10倍内。绝对差异很小,但如果写入低延迟应用程序,累积的CPU时间损失可能会很大。
long start, end;
int X = 10000000;
ArrayList l = new ArrayList(X);
start = System.nanoTime();
for(int i = 0; i < X; i++){
String.class.newInstance();
}
end = System.nanoTime();
log("T: ", (end - start)/X);
l.clear();
start = System.nanoTime();
for(int i = 0; i < X; i++){
new String();
}
end = System.nanoTime();
log("T: ", (end - start)/X);
输出:
T: 105
T: 11
测试平台为至强W3565 @3.2 1.6,Java1.6
https://stackoverflow.com/questions/647111
复制相似问题