Why is list.size()>0
slower than list.isEmpty()
in Java? On other words why isEmpty()
is preferable over size()>0
?<
.size() has to look at the entire list, while .isEmpty() can stop at the first one.
Obviously implementation dependent, but as has been said before, if you don't need to know the actual size, why bother counting all the elements?
You said:
Here
eTime-sTime>eeTime-eTime
in all cases Why?
First off, it's probably because of your testing code. You can't test the speed of calling l.size() and l.isEmpty() at the same time, since they both query the same value. Most likely calling l.size() has loaded the size of your list into your cpu cache and calling l.isEmpty() is a lot faster as a result.
You could try calling l.size() a couple of million times and l.isEmpty() a couple of million times in two separate programs but in theory the compiler could just optimize away all those calls since you're not actually doing anything with the results.
In any case, the performance difference between the two will be negligible, especially once you do the comparison you need to do to see if the list is empty (l.size() == 0
). Most likely the generated code will look almost completely similar. As some other posters noted, you want to optimize for readability in this case, not speed.
edit: I tested it myself. It's pretty much a toss-up. size()
and isEmpty()
used on Vector
gave differing results on long runs, neither beat the other consistently. When run on an ArrayList
size()
seemed faster, but not by much. This is most likely due to the fact that access to Vector
is synchronized, so what you're really seeing when trying to benchmark access to these methods is synchronisation overhead, which can be very sensitive.
The thing to take away here is that when you're trying to optimize a method call with a couple nanoseconds difference in execution time, then you're doing it wrong. Get the basics right first, like using Long
s where you should be using long
.
Counting items in a linked list can be very slow.