I'm a member of Transylvania JUG, a community from Cluj-Napoca/Romania interested in exchange of Java knowledge between members and keeping in touch with the latest Java technologies, frameworks and development trends. Attila-mihaly is a DZone MVB and is not an employee of DZone and has posted 19 posts at DZone. You can read more from them at their website. View Full User Profile

Reasons to call .isEmpty on collections

10.17.2011
| 6571 views |
  • submit to reddit

I’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.

 

From http://www.transylvania-jug.org/archives/140

Published at DZone with permission of Attila-mihaly Balazs, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

darryl west replied on Tue, 2011/10/18 - 11:40pm

thanks for the tip. I always use .isEmpty() for clarity, but it's good to know that it has potential performance benefits as well.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.