首页 > 解决方案 > CollectionUtils.isNotEmpty 和就地检查之间的性能差异

问题描述

最近在做微基准测试时,我注意到CollectionUtils.isNotEmpty方法消耗了更多时间。我认为我可能有错字或疏忽。我将代码替换为就地检查集合不为空且大小大于零。事实证明它要快得多。

我将方法 CollectionUtils.isNotEmpty 的源代码提取到我的代码中,它也更快。

是什么导致了这种差异?

注意:我知道微基准对整个 JVM 优化领域没有帮助。我特意在循环中放了 100 次,如果超过 JVM 就会优化它。检查 Windows 和 Linux 中的代码,性能差异相似。

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);
}

}

输出 :

手动就地检查所用时间为:61 µs
收集实用程序所用时间为:237193 µs
手动方法检查所用时间为:66 µs

标签: javaperformancemicrobenchmark

解决方案


可能加载类或者jar包比较耗时,可以尝试CollectionUtils.isEmpty一开始就调用。

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);
    ......

}

我的输出

Manual Inplace Check Time taken is : 10 µs 
Collection Utils Time taken is     : 21 µs 
Manual Method Check Time taken is  : 25 µs 

推荐阅读