Reputation: 2697
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?
Upvotes: 10
Views: 25383
Reputation: 1459
With the following program you can see the clear results with 1000 Integer in the List. Note: time is in milliseconds
collection.isEmpty is almost 0 milliseconds
CollectionsUtils.isNotEmpty take 78 milliseconds
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i<1000; i++)
list.add(i);
long startTime = System.currentTimeMillis();
list.isEmpty();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime);
long startTime2 = System.currentTimeMillis();
CollectionUtils.isNotEmpty(list);
long endTime2 = System.currentTimeMillis();
long totalTime2 = endTime2 - startTime2;
System.out.println(totalTime2);
}
Upvotes: 0
Reputation: 140623
The other answers are correct, but just to be sure about it:
Why do you care at all? Does your application have a performance problem; and careful profiling pointed to that method; so you are looking for alternatives?
Because ... if not ... then it could be that we are looking at PrematureOptimization.
And one other aspect: if "java standard libraries" provide a feature; I would always prefer them over something coming from an "external library". Of course, ApacheCommons is quite commons nowadays; but I would only add the dependency towards it ... if all my other code is already using it.
Upvotes: 5
Reputation: 100319
The difference is negligible (extra null check), all calls can be easily inlined even by C1 compiler. In general you should not worry about performance of such simple methods. Even if one of them is twice slower it's still blazingly fast compared to the rest code of your application.
Upvotes: 1
Reputation: 1789
Collection.isEmpty as CollectionUtils which is defined in apache libs is indirectly going to use the collection.isEmpty() method.
Although no noticable difference present in both of them, It's just that
CollectionUtils.isEmpty
is NullSafe
and as you say that you know that collection is not empty , so Both are equally Good (Almost)
Upvotes: 0
Reputation: 10662
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 ;-)
Upvotes: 12