List<Batch> vAllBatchList = getAllBatchCollection().toList(); //Has 700k records
List<Batch> vKeepableBatchCollection = getKeepableBatchCollection(pDaysKeepHistory).toList(); //has 600k records
vAllBatchList.removeAll(vKeepableBatchCollection);
Run Code Online (Sandbox Code Playgroud)
在上面的第 3 行 removeAll 方法花费了太多时间来完成。这里如何优化removeAll方法?
如果将Listof 元素转换为 remove 为 a Set,它应该更快:
vAllBatchList.removeAll(new HashSet<>(vKeepableBatchCollection));
Run Code Online (Sandbox Code Playgroud)
这是假设Batch类覆盖hashCode和equals正确。
解释:removeAllfor ArrayList(我假设你vAllBatchList List是 an ArrayList)迭代List调用它的所有元素,并检查传递的元素是否Collection包含它们。如果传递的Collection是 a Set,contains则需要预期的常数时间 ( O(1)),而如果传递的Collection是 a List,则需要线性时间 ( O(n))。
当然,如果能直接生成 aSet的元素,vKeepableBatchCollection而不是先创建 aList再转换为 a Set,那就更好了。