Why is using a loop to iterate from start of array to end faster than iterating both start to end and end to start?

后端 未结 5 749
無奈伤痛
無奈伤痛 2021-01-03 21:19

Given an array having .length 100 containing elements having values 0 to 99 at the respective indexes, where the requirem

5条回答
  •  萌比男神i
    2021-01-03 22:19

    Selected answer is excellent. I'd like to add another aspect: Try findIndex(), it's 2-3 times faster than using loops:

    const arr = Array.from({length: 900}, (_, i) => i);
    const n = 51;
    const len = arr.length;
    
    console.time("iterate from start");
    for (let i = 0; i < len; i++) {
      if (arr[i] === n) break;
    }
    console.timeEnd("iterate from start");
    
    console.time("iterate using findIndex");
    var i = arr.findIndex(function(v) {
      return v === n;
    });
    console.timeEnd("iterate using findIndex");

提交回复
热议问题