Reasons to call .isEmpty on collections
Join the DZone community and get the full member experience.
Join For Freei’ve seen many times code like the one below:
if (collection.size() > 0) { ... }
there is just something which inherently “clicks” with most programmers minds when they think “non-empty”. there is however a method which is more appropriate in most of the cases: isempty :
if (!collection.isempty()) { ... }
the top reasons for using isempty rather than size would be:
- it is more expressive (the code is easier to read and to maintain)
- it is faster, in some cases by orders of magnitude. two examples from the jdk where this is extremely visible would be the concurrentlinkedqueue and navigablemap / navigableset . all of these implement the “size” method by iterating trough the collection and because of this, calling size gets increasingly slower as the number of elements increase
todays source code
performs a comparative benchmark between small (10 element) and large
(1 000 000 elements) collections by timing the calls to the size and is
empty methods. while benchmarks and especially micro-benchmarks needs be
taken with a large grain of salt
, these tests show that there is at least a factor of 10x difference in
time when calling the size method and there is very little difference
when calling the isempty method.
Opinions expressed by DZone contributors are their own.
Comments