繁体   English   中英

CollectionUtils.isNotEmpty和就地检查之间的性能差异

[英]Performance difference between CollectionUtils.isNotEmpty and In Place check

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

我将方法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

也许加载类或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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM