JS之数组直接用include方法和数组转集合后使用has方法效率比较

JS之数组直接用include方法和数组转集合后使用has方法效率比较:

数据量小时差异可忽略,数据量大时 “数组转集合再用 has” 效率远高于数组的 includes。

核心原因是两者的查找原理不同:
1. Array.includes():本质是遍历数组逐个比对,时间复杂度为 O(n),数据越多,耗时线性增长。
2. Set.has():基于哈希表实现,查找时直接定位哈希地址,时间复杂度为 O(1),无论数据量多大,耗时基本恒定。
 
示例代码原本是使用compArr.includes方法进行判断的,现在转成集合后使用has方法,提升效率。
将数组转为集合的时间复杂度是O(n),但是Set.has()的时间复杂度是O(1),适合一次转换,多次查询的场景。
const compPropSet = new Set(compArr);
// 只遍历需要处理的组件
compList.value.forEach((comp) => {
  if (compPropSet.has(comp.prop)) {
    // 优先处理hideConfig,如果存在则隐藏
    if (labelCfg.hideConfig) {
      comp.isShow = false;
      labelVisibilityMap.set(comp.prop, false);
    } else if (labelCfg.showConfig) {
      comp.isShow = true;
      labelVisibilityMap.set(comp.prop, true);
    }
  }
});

 

posted @ 2025-09-17 16:10  罗毅豪  阅读(7)  评论(0)    收藏  举报