Why is for-in slow in javascript?

I read in several places that for-in loops are slower than looping through an array ... Although I understand that moving forward in sizeof (type) blocks is practically effortless compared to what happens behind the scenes to iterate over object keys I'm still curious what exactly the reason is that it is so slow ...

Is it necessary to make a reverse hash function to get the key, and is this process slow?

+6
source share
2 answers

The real answer to this question in the case of any particular engine is likely to depend on the implementation of this mechanism. (Like the size of the difference, if any.)

However, there are invariants. For example, consider:

var obj = {a: "alpha", b: "beta"}; var name; for (name in obj) { console.log(obj[name]); } var arr = ["alpha", "beta"]; var index; for (index = 0; index < arr.length; ++index) { console.log(arr[index]); } 

In the case of obj , the engine should use a mechanism to track those properties that you have already completed and which you don’t have, as well as filtering non-enumerable properties. For example, there is some kind of iterator object behind the scenes (and a way to define a specification, which can be a temporary array).

In the case of arr this is not so; you process this in your code in a very simple and efficient way.

The contents of the block of each cycle are the same: a search for the properties of an object. (In the latter case, theoretically, there is also a conversion of a number to a string.)

So, I expect that the only non-implementation answer would be the following: Extra overhead.

+3
source

for..each iterators and generators are used .

An iterator is an object that has a next() method. A generator is a factory function that contains yield() expressions. Both constructs are more complex than an integer index variable.

In a typical for(var i = 0; i < arr.length; i++) loop for(var i = 0; i < arr.length; i++) two commands that execute in almost all iterations are i++ and i < arr . This is probably much faster than calling a function ( next() or yield() ).

In addition, loop initiation ( var i = 0 ) is also faster than creating an iterator object using the next() method or calling a generator to create an iterator. However, this is highly implementation dependent, and the creators of the Javascript engines are doing their best to speed up such widely used language features.

I would say that the difference is so insignificant that I can spend my time optimizing other parts of the code. The choice of syntax should take into account code readability and maintainability more than performance when the performance gain is so small as to add complexity. Having said that, use the syntax that makes more sense for you and other developers who support your code after you get rich and famous !;)

+1
source

All Articles