一次job优化的总结(ListUtils.removeAll())

现象与背景是什么?

公司的一个job执行时间过长,最高时长大概:1小时45分钟。 优化后1分钟左右
image-20230423105935030

原因是什么?

抽象后耗时代码:A.removeAll(B)
集合A类型: ArrayList ,集合B类型: LinkedList

原理是什么?

ArrayList的removeAll()

若入参集合为LinkedList,则时间复杂度O(N * M),因为LinkedList的contains() 时间复杂度:O(n)
若入参集合为HashSet,则时间复杂度为O(N),因为HashSet的contains() 时间复杂度:O(1)
image-20230423110028641

image-20230423110039914

ListUtils.removeAll()方法

image-20230423110110661

方案是什么?

方案一:将B集合类型改为HashSet类型

我的方案是,但leader告诉我,batchRemove()方法如若出现System.arrrayCopy(),也会影响一定性能,让我想其他方案解决。
我的想法:创建第三个数组,用于保存不在B集合中的A集合的元素,即ListUtils.removeAll()已经帮我们实现

方案二:使用ListUtils.removeAll()方法

最后使用org.apache.commons.collections4.ListUtils.removeAll方法

最佳实践是什么?

当使用removeAll操作时,尽量使用ListUtils.removeAll() 等方法。数据量大时会有明显性能提升。

posted @ 2023-04-23 11:02  执大象  阅读(137)  评论(0)    收藏  举报