Skip to content
Advertisement

Why is list.size()>0 slower than list.isEmpty() in Java?

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

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;
     }

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?

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);
    }
}

Here eTime-sTime>eeTime-eTime in all cases. Why?

Advertisement

Answer

Your testing code is flawed.

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement