【问题标题】:Arraylist Intersection performance (in time and space ) in JavaJava中的Arraylist交集性能(时间和空间)
【发布时间】:2014-05-12 18:48:26
【问题描述】:

我需要在java中做数百万个ArrayList的交集,为此我使用了这个方法:

public static ArrayList<Integer> intersection(ArrayList<Integer> a, ArrayList<Integer> b) {
        Set<Integer> aSet = new HashSet<Integer>(a);
        Set<Integer> bSet = new HashSet<Integer>(b);

        for(Iterator<Integer> it = aSet.iterator(); it.hasNext();) {
            if(!bSet.contains(it.next())) it.remove();
        }
        return new ArrayList<Integer>(aSet);
    }

在时间方面它是高性能的但是我有很多内存泄漏,我经常会出现内存不足。如何改进功能以在时间和空间上都表现出色?

更新

输入中给出的数组列表必须保持不变。

【问题讨论】:

  • 为什么不使用removeAll()
  • 为什么要从列表开始而不是Sets?而Set.retainAll()
  • 如果您不想自己编写代码,removeAll() 是最佳选择。
  • 他想做一个交集,而不是从一个列表中删除所有值到另一个。 retainAll() 似乎是一个很好的方法。另外,如果你想经常使用集合,我建议你使用 Guava,有很多有用的方法。例如Sets.intersection(set1, set2)
  • 如果要进行真正的优化,那就是同时处理多个交叉点。你在什么条件下做交叉口?你只是在数千个数组的列表中与每一对数组相交吗?你知道哪些路口需要提前做好吗?

标签: java performance out-of-memory time-complexity space-complexity


【解决方案1】:

一种解决方案(为了提高性能)是像这样使用SortedSet

public static List<Integer> intersection2(List<Integer> a, List<Integer> b) {
    SortedSet<Integer> aSet = new TreeSet<Integer>(a);
    aSet.retainAll(b);
    return new ArrayList<Integer>(aSet);
}

另一种解决方案(用于空间)将像这样使用传入的 List(s)(EDITED 具有“新要求”,即传入的 List(s) 保持不变),

public static List<Integer> intersection3(List<Integer> a, List<Integer> b) {
    List<Integer> c = new ArrayList<Integer>(a); // <-- new requirement.
    c.retainAll(b);
    return c;
}

【讨论】:

  • 好建议。套装确实更适合那种东西
  • 我已经用这段代码 (pastebin.com/j0La75my) 测试了你的方法,但它只对很少的数组列表有效。这些是结果:pastebin.com/L1RCPqLG。我还注意到您的第二种方法返回错误的结果。
  • @IvanZandonà 这不是robust 基准。
  • 我从未想过基准测试的稳健性。但是,我尝试将您的代码插入到我的应用程序中,性能大幅下降。我已经尝试过 Guava 库,它似乎是一个以一点时间性能为代价的解决方案!
【解决方案2】:

首先你不需要在这里HashSets,你可以用一个HashSet来做到这一点。

添加从第一个 ArrayListHashSet 和的所有内容,遍历第二个 'ArrayList' 并检查是否包含在前面构造的 HashSet 中的每个元素,如果是,则将其添加到结果 ArrayList

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 2012-03-26
    • 1970-01-01
    • 2012-05-26
    • 2014-07-23
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多