大家好,我已将 ArrayList 源代码从 java.util 包复制到我自己的包中。但我发现它比原来的 java.util.ArrayList 运行解决方案。
测试代码:
@Test
public void jdkApiPerformance() {
long startTime = System.nanoTime();
java.util.ArrayList<Object> list = new java.util.ArrayList<Object>();
long costTime = System.nanoTime() - startTime;
System.out.println("jdkPerformance cost " + costTime + "ns.");
}
@Test
public void myApiPerformance() {
long startTime = System.nanoTime();
question.jdk.ArrayList<Object> list = new question.jdk.ArrayList<Object>();
long costTime = System.nanoTime() - startTime;
System.out.println("apiPerformance cost " + costTime + "ns.");
}
此测试的输出如下:
jdkPerformance cost 10263ns. apiPerformance cost 1244158ns.
Obviously, my api runs slower than JDK api.
Then I added a @Before method for this test:
@Before
public void setUp() {
new java.util.ArrayList<Object>();
new question.jdk.ArrayList<Object>();
}
此案例的输出已更改:
jdkPerformance cost 9932ns. apiPerformance cost 1324ns.
我的 api 运行速度比 JDK api 快!!?
我对这种情况感到非常困惑。请帮助我。谢谢。
最佳答案
1) 使用 System.nanoTime()
可能会给您带来扭曲的结果,因为它取决于操作系统的调度程序粒度:
This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().
2)要获得有意义的基准测试,您必须首先预热 JVM
3)为了进行研究,您可以使用基准测试库之一:
4) 一般来说,你的问题的答案是:是,在某些情况下,Sun/Oracle 的 JVM 会热替换一些 JDK 代码,例如 Math.sqrt()
针对给定操作系统/硬件优化了实现。
关于api - JDK对自己的api有一些优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15214322/