返回列表

includes性能对比for循环

默认分类 2018/09/03 07:56

实测includes效率比for要高很多,因此建议使用includes,记得自己处理 100 !== '100'的情况

var aa = []; // [0, 1, 2, 3, ...]
for (let i = 0; i < 1000000; i++) {aa.push(i)}
console.time('for');
for (let i = 0, len = aa.length; i < len; i++) {
  if (aa[i] === 999999) {
    break
  }
}
console.timeEnd('for')
console.time('includes')
aa.includes(999999)
console.timeEnd('includes')
// 耗时: for: 4.921142578125ms
// 耗时: includes: 2.369140625ms

var aa = []; // [0, 1, 2, 3, ...]
for (let i = 0; i < 1000000; i++) {aa.push(i)}
console.time('for');
for (let i = 0, len = aa.length; i < len; i++) {
  if (aa[i] === 1) {
    break
  }
}
console.timeEnd('for')
console.time('includes')
aa.includes(1)
console.timeEnd('includes')

// 耗时: for: 0.04296875ms
// 耗时: includes: 0.006103515625ms

undefined
var aa = []; // [0, 1, 2, 3, ...]
for (let i = 0; i < 1000000; i++) {aa.push(i)}
console.time('for');
for (let i = 0, len = aa.length; i < len; i++) {
  if (aa[i] === 100000) {
    // console.log(true)
    break
  }
}
console.timeEnd('for')
console.time('includes')
aa.includes(100000)
console.timeEnd('includes')

// 耗时: for: 2.329833984375ms
// 耗时: includes: 0.373779296875ms