Skip to main content
added 310 characters in body
Source Link
Bálint
  • 15.1k
  • 2
  • 38
  • 57

The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.

Details:

I just created an array with 10,000,000 elements, each being equal to its index ([0, 1, 2, 3...]), then added their squares to a number to make sure it doesn't get optimized out. The forEach method came out at an average of 1407ms and the normal for method came out at 1443ms with 20 test runs.

The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.

The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.

Details:

I just created an array with 10,000,000 elements, each being equal to its index ([0, 1, 2, 3...]), then added their squares to a number to make sure it doesn't get optimized out. The forEach method came out at an average of 1407ms and the normal for method came out at 1443ms with 20 test runs.

Source Link
Bálint
  • 15.1k
  • 2
  • 38
  • 57

The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.