Search code examples
javascriptarraysoptimizationtraversal

Array traversal magnitudes faster after removing the first element


After reading the recent smashing magazine article on optimisation, I ran some tests to see what would be the most effective way of "deleting" an element from the middle of one of my arrays.

After running my own tests regarding splicing a value out from the middle of the array vs deleting it/setting it to null, I came across the rather unexpected result that splicing the value out from the array made the array an order of magnitude faster to traverse.

More investigation led me to this.

For some reason, .shift()'ing the first record from the array made it 300 times faster to traverse (the biggest performance being seen in v8, but it seems to be valid for all the browsers I've tried it in).

I doubt I'll abuse this as I don't think the actual traversal is a bottleneck, but does anyone know why this behaviour occurs?

Edit: Incorrect use of jsPerf was the underlying issue here, see my answer below.


Solution

  • Okay, it turns out this is actually a misunderstanding on my part of how jsPerf works.

    The setup section of the script is something that's run at the beginning of each set of loops rather than running it everytime it tries the script.

    As shown here the numbers actually turn out as you'd expect.