for-in vs Object.keys forEach without inherited properties

后端 未结 6 1926
萌比男神i
萌比男神i 2020-12-15 03:19

I was looking at a perf benchmark of Object.keys + forEach vs for-in with normal objects.

This benchmark shows that Obj

6条回答
  •  囚心锁ツ
    2020-12-15 03:54

    For anyone viewing still concerned with iterating object properties in JS, the absolute fastest method is:

    var keys = Object.keys(obj), i = keys.length;
    
    while(--i) {
       //
    }
    

    http://jsperf.com/object-keys-foreach-vs-for-in-hasownproperty/8

    You can save a bit on large objects by not having to recompute the length value of the key array (mostly negligible with modern browser optimizations), which is also true for the case of a simple for loop. The decremented while loop is still faster than the for loop or the incremented while loop with length upper limit comparison, by a fair margin.

提交回复
热议问题