【问题标题】:Subtracting one ArrayList form another performance从另一个性能中减去一个 ArrayList
【发布时间】:2018-03-02 16:17:34
【问题描述】:

我想从另一个 ArrayList 中减去一个

@ToString
@EqualsAndHashCode
class Person
{
    PersonGender gender
    String name
    String surname
}

static def substractList(ArrayList<Person> listOne, ArrayList<Person> listTwo) {
    listOne.minus listTwo
    // listOne has 200k elements
    // listTwo has 170k elements
}

代码已运行40分钟,但无法完成。
如何让执行更快?

【问题讨论】:

    标签: performance optimization groovy collections


    【解决方案1】:

    Person 是否实现了Comparable?如果是这样,Groovy 将执行 1,046,089 次操作。如果不是,它将走较慢的路径并执行 34,000,000,000 次操作 (see the code for minus here)

    所以你应该可以通过让Person 实现Comparable 使其速度提高 34,000 倍,然后 Groovy 将使用 TreeSet;将所有listOne 添加到其中,然后删除所有listTwo

    如果你不能让它具有可比性……嗯……你能对列表进行预排序吗?

    如果是这样,我们也许可以提出一种算法,同时遍历两个列表...并且 可能更快...

    【讨论】:

    • 在普通 Java 中,您将使用 listOne.removeAll(new HashSet&lt;&gt;(listTwo))O(n) 中执行此操作。如果您需要新列表,请在前面添加 listOne = new ArrayList&lt;&gt;(listOne)
    猜你喜欢
    • 2012-04-13
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多