api - JDK对自己的api有一些优化吗?

标签 api arraylist jvm java

大家好,我已将 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/

相关文章:

javascript - 在 Svelte 中检索 JSON 数据

java - 确定二进制数的间隙长度

java - JPype/Java - 初始化或获取剩余堆空间

php - PayPal REST API 交叉引用交易与支付

php - Tumblr API 上传

android - OLA API 集成给出错误作为无效的合作伙伴 key

ArrayList 和 RecyclerView 的 java.lang.OutOfMemoryError

java - 在Android中的Arraylist上执行AsyncTask来更新数据库

共享 Linux Web 服务器 (JustHost) 上的 JavaVM

java - 为什么从串行GC切换到G1会增加RSS