英文:
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
类正确重写了 hashCode
和 equals
的前提下。
解释:对于 ArrayList
(我假设您的 vAllBatchList
是一个 ArrayList
),removeAll
方法会迭代调用它的 List
的所有元素,并检查传入的 Collection
是否包含它们。如果传入的 Collection
是一个 Set
,contains
操作将以预期的常数时间 (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<>(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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论