0

Where y is an array of objects,

y = [
    {property:"",property2:""},
    {property:"",property2:""},
    {property:"",property2:""},
    {property:"",property2:""},
    {property:"",property2:""}
]

could someone please tell me why,

for (x in y) {
    console.log(x[y].property);
}

is so many times slower than,

for (i = 0; i < y.length; i++) {
    console.log(x[y].property);
}
A Person
  • 75
  • 7
  • the equivalent in your first example would be `for( x of y ) { ... }` and not `in`. – Sirko Jun 22 '18 at 16:08
  • 1
    If x is an array, it should be `for (y in x) {`... – Kosh Jun 22 '18 at 16:15
  • what is your environment ? browser (which one and which version?) or other (node.js ? ...). Which OS ? The language in itself doesn't have performance, implementations (JavaScript engines) have. – Pac0 Jun 22 '18 at 16:18

1 Answers1

4

In the following benchmark; you i'll see that in chrome version 62.0.3202, for...in... is faster.

The speed of one or another looping style is depending on the javascript engine running it.

So if you want to know which one is faster and why you should start to look at the node.js version you are using; and then look for explaination about how the specific engine is made.

enter image description here


In this other benchmark about node.js from v5.x to v6.x.

You see how much the speed has changed

enter image description here

So if in v5.1.281.102 it was way more optimized to use a for-in, in v6.1.361 it's better to use Object.keys associated to a for loop.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69