Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-in vs Object.keys forEach without inherited properties

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

This benchmark shows that Object.keys + forEach is 62% slower than the for-in approach. But what if you don't want to get the inherited properties? for-in includes all non-native inherited objects, so we'll have to use hasOwnProperty to check.

I tried to make another benchmark here doing exactly that. But now the for-in approach is 41% slower than Object.keys + forEach.


update

The above test was done in Chrome. Tested it again but with Safari and I'm getting different results: Object.keys(..).forEach(..) 34% slower, odd.

Note: The reason I'm benchmarking is to check how it is with Node.js.

Questions:

  • Are the jsperf result for Chrome considerable for Node.js?
  • What happened, how come a single conditional made the for-in approach 41% slower than Object.keys + forEach in Chrome?
like image 974
majidarif Avatar asked Jul 31 '14 07:07

majidarif


People also ask

Can we apply forEach on object?

JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object.

What line of code is used to iterate through all the properties of an object?

Description. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).

Does object keys preserve order?

YES (but not always insertion order). Most Browsers iterate object properties as: Integer keys in ascending order (and strings like "1" that parse as ints) String keys, in insertion order (ES2015 guarantees this and all browsers comply)


1 Answers

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.

like image 183
MaxArt Avatar answered Sep 29 '22 06:09

MaxArt