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?
Basically, in implementations of some lists the method isEmpty() checks if the size is zero (and therefore from the point of view of performance they are practically equivalent). In other types of lists (for example the linked lists), however, counting items require more time than to check if it is empty or not.
size() can be O(1) or O(N), depending on the data structure ; . isEmpty() is never O(N).
The size of an empty ArrayList is zero. ArrayList.
isEmpty() doesn't check if a list is null . If you are using the Spring framework you can use the CollectionUtils class to check if a list is empty or not.
For ArrayList
, yes — you are correct that the operations take (roughly) the same time.
For other implementations of List
— for example, a naïve linked list* — counting the size might take a very long time, while you only actually care whether it is greater than zero.
So if you absolutely know that the list is an implementation of ArrayList
and will never ever change, then it does not really matter; but:
size() == 0
is still not faster than isEmpty()
, so there is no compelling reason to ever use the former.isEmpty()
is a clearer definition of what it is you actually care about and are testing, and so makes your code a bit more easily understandable.* I originally wrote LinkedList here, implicitly referencing java.util.LinkedList
, though that particular implementation does store its size explicitly, making size()
an O(1) operation here. A naïve linked list operation might not do this, and in the more general sense there is no efficiency guarantee on implementations of List
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With