【问题标题】:Apache CollectionUtils PerformanceApache CollectionUtils 性能
【发布时间】:2014-08-21 12:55:36
【问题描述】:

如果有人对 Apache CollectionUtils 进行了基准测试,我正在徘徊。 在我的简单基准测试中:

List<Integer> ints = Arrays.asList(3, 4, 6, 7,8, 0,9,2, 5, 2,1, 35,11, 44, 5,1 ,2);
    long start = System.nanoTime();
    ArrayList<Integer> filtered = new ArrayList<Integer>(ints.size());
    for (Integer anInt : ints) {
        if (anInt > 10) {
            filtered.add(anInt);
        }
    }
    long end = System.nanoTime();
    System.out.println(filtered + " (" + (end - start) + ")");

    Predicate<Integer> predicate = new Predicate<Integer>() {
        @Override
        public boolean evaluate(Integer integer) {
            return integer > 10;
        }
    };
    start = System.nanoTime();
    filtered.clear();
    CollectionUtils.select(ints, predicate,filtered);
    end = System.nanoTime();
    System.out.println(filtered + " (" + (end - start) + ")");

我得到了以下结果:

[35, 11, 44] (127643)
[35, 11, 44] (3060230)

我必须说我是这个库的忠实粉丝,因为它使代码干净且可测试,但目前我正在从事性能敏感项目,我担心我对这个库的喜爱会损害性能。

我知道这是一个非常普遍的问题,但是有人将这个库用于生产环境吗?并注意到性能问题?

【问题讨论】:

  • 您应该多次运行它。您可能不会只运行一次就看到 JVM 优化,因为它会进行优化。不同之处仅在于您的代码直接调用,而 CollectionUtils 每次都使用正在评估的谓词。
  • @NoDataFound 在这种情况下(评估)使用 Predicate Transformer 或 Closure 总是会更慢直接编写代码与运行多少时间无关
  • @Joe 是怎么重复的?问题不是专门针对这个基准的,我对 Apache 的 CollectionUtils 进行了更一般的性能...您可能会将其标记为懒惰的开发人员 :) 因为我试图找到已经以更专业的方式完成此基准测试的人,我可能会做。由于这是一个非常常见的 Apache 库,我认为它是一个值得共享的重要基准。

标签: performance apache benchmarking apache-commons-collection


【解决方案1】:

除了多次运行它以检查 JVM 优化(我不知道是否鉴于 Predicate 可以是一个函数式接口,JVM 不能使用 Java 7 中引入的新字节码关键字invokedynamic),我认为您在 start 之后错误依赖:

start = System.nanoTime();
filtered.clear();
CollectionUtils.select(ints, predicate,filtered);
end = System.nanoTime();
System.out.println(filtered + " (" + (end - start) + ")");

如果您想检查 CollectionUtils 和普通旧 foreach 之间的差异,我认为您不应该评估 filtered.clear() 的工作时间。

【讨论】:

  • 好点,但我也应该避免在第一个循环中创建 ArrayList。我的假设是清除和创建新实例应该相等(或者甚至创建新实例应该更长)
  • 我的意思是你在比较同一个函数的两个实现,但是你考虑到了不应该的操作。所以是的,new ArrayList() 不应该被考虑,因为select 使用已经存在的列表。
【解决方案2】:

嗯,您基本上是在将方法调用开销与内联代码进行比较,后者显然更快。

只要您不做任何真正挑战您的 CPU 的事情,如果这会导致您的应用程序出现性能问题,我会感到非常惊讶。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2017-02-04
    • 2015-11-06
    • 2012-01-04
    • 2015-09-29
    • 2016-01-06
    相关资源
    最近更新 更多