for-in vs Object.keys forEach without inherited properties

后端 未结 6 1936
萌比男神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:55

    node.js uses V8, although I guess it's not the same as the current version in Chrome, but I guess it's a good indicator of node's performances on the subject.

    Secondarily, you're using forEach, which is quite handy when developing but adds a callback for every iteration, and that's a (relatively) lenghty task. So, if you're interested in performances, why don't you just use a normal for loop?

    for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
        // ...
    }
    

    This yields the best performances you can get, solving your speed problems in Safari too.

    In short: it's not the conditional, it's the call to hasOwnProperty that makes a difference. You're doing a function call at every iteration, so that's why for...in becomes slower.

提交回复
热议问题