1) There are many different ways to enumerate properties:
for..in
(iterates over enumerable properties of the object and its prototype chain)
Object.keys(obj)
returns the array of the enumerable properties, found directly on the object (not in its prototype chain)
Object.getOwnPropertyNames(obj)
returns an array of all properties (enumerable or not) found directly on the object.
- If you're dealing with multiple objects of the same "shape" (set of properties), it might make sense to "pre-compile" the iteration code (see the other answer here).
for..of
can't be used to iterate an arbitrary object, but can be used with a Map
or a Set
, which are both suitable replacements for ordinary Objects for certain use-cases.
- ...
Perhaps if you stated your original problem, someone could suggest a way to optimize.
2) I find it hard to believe that the actual enumeration is taking more than whatever you do with the properties in the loop body.
3) You didn't specify what platform you're developing for. The answer would probably depend on it, and the available language features depend on it too. E.g. in SpiderMonkey (Firefox JS interpreter) circa 2009 you could use for each(var x in arr)
(docs) if you actually needed the values, not the keys. It was faster than for (var i in arr) { var x = arr[i]; ... }
.
V8 at some point regressed the performance of for..in
and subsequently fixed it. Here's a post on the internals of for..in
in V8 in 2017: https://v8project.blogspot.com/2017/03/fast-for-in-in-v8.html
4) You probably just didn't include it in your snippet, but a faster way to do a for..in
iteration is to make sure the variables you use in the loop are declared inside the function containing the loop, i.e.:
//slower
for (property in object) { /* do stuff */ }
//faster
for (var property in object) { /* do stuff */ }
5) Related to (4): while trying to optimize a Firefox extension I once noticed that extracting a tight loop into a separate function improved its performance (link). (Obviously, it doesn't mean you should always do that!)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…