array traversal recommended through

for(var i = 0; i < ar.length; i++) { console.log(ar[i]); } 

but this approach does not provide for holes in the array.

If there are deleted elements in the array, there is such a processing method:

 for(var o of ar) { console.log(o); } 

but processing speed drops

I have 1 000 000 records. The difference in methods gave a 20-fold slowdown in processing.

 var ar = new Array(1000000); ar.fill(1); console.time(); for(var i = 0; i < ar.length; i++) { ar[i] = 2; } console.timeEnd(); console.time(); for(var o of ar) { o = 2; } console.timeEnd(); 

maybe there is a third way that gives good speed and the necessary flexibility in processing large arrays?

UPDATE

The proposed Леша Марченковский version gives a good speed increase on holey arrays:

 var br = new Array(10000000); for(var i = 0; i < 1000000; i++){ var l = parseInt(Math.random() * 1000000); br[i] = 1; } console.time(); for(var i = 0; i < br.length; i++) { if(br[i] == undefined) continue; br[i] = 2; } console.timeEnd(); console.time(); for(var o of br) { o = 2; } console.timeEnd(); 

default: 1365.980ms

default: 6656.250ms

  • all methods in the array, such as forEach, map, etc. miss holes. Their performance depends on the browser implementation - Grundy
  • In general, such measurements are a thankless task. You can never be sure what you measured. And whether this test will show the necessary data, and not just be thrown out, as doing nothing. For example, in FF, measurement results differ by less than a millisecond. - Grundy
  • I have processed a million records for 70 ms in the second case (and 30 in the first). This value is comparable with the accuracy of the HTTP request execution time. Do you really have such big data that the difference becomes noticeable? - etki
  • @Grundy, but on nodeJS? IMHO: forEach and map create extra entities -> memory consumption - ravend
  • @etki, I have 6ms vs. 125ms - ravend

1 answer 1

To handle the so-called "holes", use the construction

 if (i in arr) {} 
  • 2
    this is not enough, the value undefined Does not guarantee the presence of a hole. The presence of a hole ensures that there is no corresponding numeric key. - Grundy
  • Yes, this code will work incorrectly in the case of undefined values ​​in the array elements themselves. But to achieve the desired result, you can replace undefined with something like null - Lesha Marchenkovsky
  • Instead of strict checking for undefined and for null, you can use lax for null. - Arnial
  • 2
    Then if (i in arr) - vp_arth
  • one
    @Arnial, [undefined,null] - this is an array in which there are no holes - Grundy