Why is list.size()>0 slower than list.isEmpty() in Java?
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:
- This is bad programming practice to tie yourself down to a specific implementation.
- If things change a few years down the line with code restructuring, testing will show that "it works," but things are running less efficiently than before.
- Even in the best case,
size() == 0
is still not faster thanisEmpty()
, 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
.
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.
I'm sorry, but your benchmark is flawed. Take a look at Java theory and practice: Anatomy of a flawed microbenchmark for a general description on how to approach benchmarks.
Update: for a proper benchmark you should look into Japex.