Recently while I was doing a micro-benchmark , I noticed that the CollectionUtils.isNotEmpty method consumed more time. I thought there might be a typo or oversight from me. I replaced the code with in place check of collection is not null and size is greater than zero. It proved to be much faster.
I pulled the source code of method CollectionUtils.isNotEmpty into my code and it is faster as well.
What causes this difference?
Note: I know micro-benchmark is not going to help in the whole realm of JVM optimization. I specifically put for 100 times in the loop , if it is more than JVM is going to optimize it. Checked the code in Windows and Linux and the performance difference is similar.
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class TestCollectionUtilsPerf {
public static void main(String[] args) {
List<String> stringList = Arrays
.asList(new String[] { "StringOne", "StringTwo", "StringThree", "StringFour", "StringFive" });
long startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (stringList != null && stringList.size() != 0) {
continue;
}
}
System.out.format("Manual Inplace Check Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (CollectionUtils.isNotEmpty(stringList)) {
continue;
}
}
System.out.format("Collection Utils Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (isNotEmpty(stringList)) {
continue;
}
}
System.out.format("Manual Method Check Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
}
public static boolean isEmpty(final Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
return !isEmpty(coll);
}
}
Output :
Manual Inplace Check Time taken is : 61 µs
Collection Utils Time taken is : 237193 µs
Manual Method Check Time taken is : 66 µs
Maybe It took a lot of time to load the class or the jar package,You can try to call CollectionUtils.isEmpty
at the very beginning.
public static void main(String[] args) {
List<String> stringList = Arrays
.asList(new String[] { "StringOne", "StringTwo", "StringThree", "StringFour", "StringFive" });
//try it at the begging to load the class
CollectionUtils.isEmpty(stringList);
......
}
and my outbut
Manual Inplace Check Time taken is : 10 µs
Collection Utils Time taken is : 21 µs
Manual Method Check Time taken is : 25 µs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.