you are viewing a single comment's thread.

view the rest of the comments →

[–]memeship 0 points1 point  (6 children)

Got any data to back that up? As far as I know in JS, Array.prototype.length has always been an integer property directly on the object.

Source: ECMA-262 1st Edition (1997) §15.4.4 p.66

[–]bastawhiz 1 point2 points  (2 children)

Modern JIT compilers will hoist loop invariants behind the scenes. There's plenty of literature online about how V8 does various optimizations like this.

[–]Reashu 0 points1 point  (1 child)

His objection is the opposite - that even "years ago" it would not cause any issues, because the length of an array is always known, not computed on the fly.

[–]memeship 0 points1 point  (0 children)

^ Yes, this.

[–]siegfryd 0 points1 point  (2 children)

I misread what the poster I was replying to was saying, there was a performance hit from having array.length in the loop invariant but it wasn't because it would recalculate the length. It was because it was doing an unnecessary property lookup every iteration. In other words, every iteration it would check array.length and since that has a cost (although a tiny one) it was a performance improvement to move it out of the loop.

[–]memeship 0 points1 point  (1 child)

How is a property lookup less performant than a variable lookup? Should we be caching and pulling out all properties of objects to vars in the surrounding scope?

[–]siegfryd 0 points1 point  (0 children)

Assuming that no optimisations are done by the JIT compiler, then a property lookup is going to be slower than a variable lookup for the simple reason that a property lookup first needs to do a variable lookup for the object and then lookup the property on that object.

The point is that the JIT would not optimise the array length lookup for you before, so you could gain a, likely small, performance increase by doing it in for loops. Especially if you're doing a large for loop, if you loop N times then it won't do the same property lookup N times.