Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better for the performance CollectionUtils.isEmpty() or collection.isEmpty()

What is better for the performance if you already know that the collection isn’t null. Using !collection.isEmpty() or CollectionUtils.isNotEmpty(collection) from the Apache Commons lib?

Or isn’t there any performance difference?

like image 844
Danny Gloudemans Avatar asked Jul 29 '15 12:07

Danny Gloudemans


People also ask

What does CollectionUtils isEmpty do?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.

What is Apache Commons collections used for?

The Apache Commons Collections is a project used to develop and maintain a collection of classes based on and inspired by the Java Development Kit (JDK) collection framework. This group of collections includes features such as: Bag interfaces for collections that have a number of copies of each object.

What is CollectionUtils?

Simply put, the Apache CollectionUtils provides utility methods for common operations which cover a wide range of use cases and helps in avoiding writing boilerplate code. The library targets older JVM releases because currently, similar functionality is provided by the Java 8's Stream API.

How do you check if the collection is empty or not in Java?

The size() and isEmpty() of java. util. Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value.


1 Answers

The code of CollectionUtils.isNotEmpty (assuming we are talking about Apache Commons here)...

public static boolean isEmpty(Collection coll)
{
    return ((coll == null) || (coll.isEmpty()));
}

public static boolean isNotEmpty(Collection coll)
{
    return (!(isEmpty(coll)));
}

...so, not really a difference, that one null check will not be your bottleneck ;-)

like image 116
Florian Schaetz Avatar answered Sep 19 '22 10:09

Florian Schaetz