Comparasion of Integer.equals() and Objects.equals()

☆樱花仙子☆ 提交于 2019-12-24 06:42:01

问题


Here are my test for two equals methods:

    Random generator = new Random();
    long startTime = System.nanoTime();
    for(int i = 0; i<1000; i++) {
        Integer int11 = generator.nextInt(1000);
        Integer int22 = generator.nextInt(1000);
        int11.equals(int22);            
    }
    long endTime = System.nanoTime();
    long duration = (endTime - startTime); 
    System.out.println(duration + " ns");

    Random generator1 = new Random();
    long startTime1 = System.nanoTime();
    for(int i = 0; i<1000; i++) {
        Integer int1 = generator1.nextInt(1000);
        Integer int2 = generator1.nextInt(1000);
        Objects.equals(int1, int2);
    }
    long endTime1 = System.nanoTime();
    long duration1 = (endTime1 - startTime1); 
    System.out.println(duration1 + " ns");

I just wanted to know, how much slower is the Objects.equals() method, but I got following output:

1005750 ns
650554 ns

When I replaced these two methods:

    Random generator1 = new Random();
    long startTime1 = System.nanoTime();
    for(int i = 0; i<1000; i++) {
        Integer int1 = generator1.nextInt(1000);
        Integer int2 = generator1.nextInt(1000);
        Objects.equals(int1, int2);
    }
    long endTime1 = System.nanoTime();
    long duration1 = (endTime1 - startTime1); 
    System.out.println(duration1 + " ns");

    Random generator = new Random();
    long startTime = System.nanoTime();
    for(int i = 0; i<1000; i++) {
        Integer int11 = generator.nextInt(1000);
        Integer int22 = generator.nextInt(1000);
        int11.equals(int22);            
    }
    long endTime = System.nanoTime();
    long duration = (endTime - startTime); 
    System.out.println(duration + " ns");

I get very similar output to the previous one:

1026871 ns
614074 ns

So, my question is: Why does the second "test" execute much faster than the first one in both cases? What does it depend on?


回答1:


Because the JIT kicks in, and detects that Random.nextInt() and equals() are two methods that are often called, and that optimizing them is thus useful.

Once the byte-code is optimized and transformed to native code, its execution is faster.

Note that what you're measuring is probably more Random.nextInt() than equals().

Correct micro-benchmarks are extremely hard to do right in Java, due to the runtime optimizations done by the JIT, and due to garbage collection. If you want to be serious about it, use JMH.



来源:https://stackoverflow.com/questions/30983487/comparasion-of-integer-equals-and-objects-equals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!