如何高效拆分百万级数组?按条件拆分userTraveled为inLondon与notInLondon
高效拆分大数组的最优方案
你的原始代码存在严重性能瓶颈:london.includes(p) 每次检查都需要遍历整个1000万条数据的数组,对于百万级的userTraveled来说,整体时间复杂度是O(M*N)(M为userTraveled长度,N为london长度),运算量达到1e13级别,完全无法高效处理。
最优方案是利用Set的O(1)查找特性,先将london数组转换为Set,再遍历userTraveled进行判断,整体时间复杂度降到O(M+N),性能提升几个数量级。
具体实现代码
首先将大数组转换为Set:
// 将london数组转为Set,单次遍历O(N) const londonSet = new Set(london);
然后用普通for循环拆分(大数据量下性能略优于forEach/reduce):
const inLondon = []; const notInLondon = []; for (const place of userTraveled) { if (londonSet.has(place)) { inLondon.push(place); } else { notInLondon.push(place); } }
如果偏好函数式风格,也可以用reduce:
const { inLondon, notInLondon } = userTraveled.reduce((result, place) => { result[londonSet.has(place) ? 'inLondon' : 'notInLondon'].push(place); return result; }, { inLondon: [], notInLondon: [] });
补充说明
- Set会自动去重london中的重复元素,这不仅不影响存在性判断,还能减少内存占用,对性能友好。
- 大数据量下,普通for循环的性能通常优于forEach、map等数组方法,因为减少了函数调用的开销。
内容的提问来源于stack exchange,提问作者Ibrahim Ali
相关产品推荐
相关产品推荐

