removeAll()方法花费了很长时间。

huangapple go评论74阅读模式
英文:

removeAll() method is taking long time

问题

vAllBatchList.removeAll(vKeepableBatchCollection);

在上述第三行中,removeAll 方法花费了太多时间来完成。如何在这里优化 removeAll 方法?

英文:
List<Batch> vAllBatchList = getAllBatchCollection().toList(); //Has 700k records
List<Batch> vKeepableBatchCollection = getKeepableBatchCollection(pDaysKeepHistory).toList(); //has 600k records
vAllBatchList.removeAll(vKeepableBatchCollection);

In the above 3rd line removeAll method is taking too much time to finish. How to optimize the removeAll method here?

答案1

得分: 7

如果您将要移除的元素的 List 转换为一个 Set,那么速度会更快:

vAllBatchList.removeAll(new HashSet<>(vKeepableBatchCollection));

这是在假设 Batch 类正确重写了 hashCodeequals 的前提下。

解释:对于 ArrayList(我假设您的 vAllBatchList 是一个 ArrayList),removeAll 方法会迭代调用它的 List 的所有元素,并检查传入的 Collection 是否包含它们。如果传入的 Collection 是一个 Setcontains 操作将以预期的常数时间 (O(1)) 运行,而如果传入的 Collection 是一个 List,则会花费线性时间 (O(n))。

当然,如果您可以直接生成一个 vKeepableBatchCollection 元素的 Set,而不是先创建一个 List,然后再将其转换为 Set,效果会更好。

英文:

If you convert the List of element to remove to a Set, it should be faster:

vAllBatchList.removeAll(new HashSet&lt;&gt;(vKeepableBatchCollection));

This is assuming Batch class overrides hashCode and equals properly.

Explanation: removeAll for ArrayList (I'm assuming your vAllBatchList List is an ArrayList) iterates over all the elements of the List on which it is called, and checks if the passed Collection contains them. If the passed Collection is a Set, contains will take expected constant time (O(1)), while if the Collection is a List, it will take linear time (O(n)).

Of course, if you can directly generate a Set of the elements of vKeepableBatchCollection instead of first creating a List and then converting it to a Set, it would be even better.

huangapple
  • 本文由 发表于 2020年3月16日 18:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/60703843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定