Friday 10 February 2012

`forEach` and runtime cost

Just a tiny one today, mostly to write this down somewhere:

As you all know, ECMAScript5 adds forEach to arrays, where you supply a function that gets called for each element in the array. There are lots of benefits to this, not least variable scoping on the index and value variables and a bit less typing, but don't all of those function calls add up to a significant runtime cost?

No, they don't.

I got curious about it (I have a tendency to micro-optimize, which I'm trying to break myself of), so I tested it on the slowest (desktop) browser currently in use: IE6. Specifically, IE6 running in an old Windows 2000 VM I have lying around. I tested the performance of looping through a 100-entry array both with and without calling a function. Without the function call, IE6 looped through the array ~4,500 times in a second (that's 450,000 loop iterations/second). With the function, it managed ~2,000 times a second (200,000 loop iterations/second). So while that's a big relative difference (56% slower!), in real terms it falls into fergedaboudit territory: 2.78 microseconds of overhead. You heard, me, microseconds. That's 0.00278 milliseconds.

Now, I'm not going to say there aren't places where it could matter. I am going to say that they're going to be extraordinarily rare, I'd wager I'll never run into a situation where it makes a difference and nor will you. Whatever else you're doing in the loop body is totally going to wash out the function calls. Really.

Happy coding!

4 comments:

cyberplus1 said...

I will probably safe this few microseconds. Microptimizations...

Tim said...

I would actually not test this in IE6 since the JavaScript engine is so poorly implemented that it might not be even able to optimize a (function call in a) for-loop. Today's browser do extremely good jobs at analyzing and optimizing critical parts of the code, I would say that there wouldn't be any significant difference for wrapping a block of code in a function call.
Besides IE6 doesn't represent today's browsers anymore.

Still a interesting article!

T.J. Crowder said...

@Tim - That was the whole point (as I said in the post): I used the oldest, slowest browser I could find, figuring if it didn't cause enough overhead to matter on that thing, it wouldn't matter on the rather better browsers we have today.

Angel17 said...

Thanks for sharing this post. This is so helpful! vacation rental property manager Siesta Key, FL