Java基准测试 - 为什么第二个循环更快? [英] Java benchmarking - why is the second loop faster?

查看:126
本文介绍了Java基准测试 - 为什么第二个循环更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此感到好奇。

我想检查哪个功能更快,所以我创建了一些代码并执行了很多次。

I wanted to check which function was faster, so I create a little code and I executed a lot of times.

public static void main(String[] args) {

        long ts;
        String c = "sgfrt34tdfg34";

        ts = System.currentTimeMillis();
        for (int k = 0; k < 10000000; k++) {
            c.getBytes();
        }
        System.out.println("t1->" + (System.currentTimeMillis() - ts));

        ts = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            Bytes.toBytes(c);
        }
        System.out.println("t2->" + (System.currentTimeMillis() - ts));

    }

第二循环更快,所以,我想hadoop的Bytes类比String类的函数快。然后,我改变了循环的顺序,然后c.getBytes()变得更快。我执行了很多次,我的结论是,我不知道为什么,但是在第一个代码执行后我的VM中发生了一些事情,因此第二个循环的结果变得更快。

The "second" loop is faster, so, I thought that Bytes class from hadoop was faster than the function from String class. Then, I changed the order of the loops and then c.getBytes() got faster. I executed many times, and my conclusion was, I don't know why, but something happen in my VM after the first code execute so that the results become faster for the second loop.

推荐答案

这是一个经典的Java基准测试问题。 Hotspot / JIT / etc会在您使用它时编译您的代码,因此它在运行期间会变得更快。

This is a classic java benchmarking issue. Hotspot/JIT/etc will compile your code as you use it, so it gets faster during the run.

在循环中运行至少3000次(在服务器上运行10000次)或者在64位上) - 然后进行测量。

Run around the loop at least 3000 times (10000 on a server or on 64 bit) first - then do your measurements.

这篇关于Java基准测试 - 为什么第二个循环更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆