本文介绍了为什么list.size()> 0比Java中的list.isEmpty()慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 list.size()> 0 比Java中的 list.isEmpty()慢?换句话说,为什么 isEmpty()优于 size()> 0

Why is list.size()>0 slower than list.isEmpty() in Java? On other words why isEmpty() is preferable over size()>0?

当我查看 ArrayList 中的实现时,看起来速度应该是相同的:

When I look at the implementation in ArrayList, then it looks like the speed should be the same:

ArrayList.size()

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
      return size;
    }

ArrayList.isEmpty()

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    public boolean isEmpty() {
        return size == 0;
     }

如果我们只是编写一个简单的程序来获取两种方法的时间,那个案例 size()在所有情况下都需要更多 isEmpty(),为什么会这样呢?

If we just write a simple program to get the time take by both the methods, that case size() will take more isEmpty() in all cases, why this so?

这是我的TestCode;

Here is my TestCode;

import java.util.List;
import java.util.Vector;

public class Main {
    public static void main(String[] args) {
        List l=new Vector();
        int i=0;
        for(i=0;i<10000;i++){
            l.add(new Integer(i).toString());
        }
        System.out.println(i);
        Long sTime=System.nanoTime();
        l.size();
        Long eTime=System.nanoTime();
        l.isEmpty();
        Long eeTime=System.nanoTime();
        System.out.println(eTime-sTime);
        System.out.println(eeTime-eTime);
    }
}

此处 eTime-sTime>在所有情况下都是eeTime-eTime 。为什么?

推荐答案

您的测试代码存在缺陷。

Your testing code is flawed.

只需反向顺序,即先调用isEmpty,然后调整大小> 0秒,你将获得相反的结果。这是由于类加载,缓存等。

Just reverse the order, i.e call isEmpty first and size > 0 second and you'll get the opposite result. This is due to class loading, caching, etc.

这篇关于为什么list.size()&gt; 0比Java中的list.isEmpty()慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 07:33