4

My question is spawned by the Jsperf here:

http://jsperf.com/the-fastest-way-to-truncate-an-array/7

The setup code:

Benchmark.prototype.setup = function() {
 var test_array = [];
 for (var j=0; j< 10000; j++){
 test_array[j] = 'AAAAAAAAAA';
 }
};

And the tests:

// Array.slice() method
result = test_array.slice(0,100);
// Array.splice() method
test_array.splice(100);
// Modifying Array.length
test_array.length = 100;
// Array.pop() method
while (test_array.length > 100) test_array.pop();

JSPerf's result shows that the Array.pop() method is completing faster than the others by a large margin - upwards of 80 times faster on some implementations.

What's going on here? Is Array.pop() in a loop really this much faster than the other tests? Is there a flaw in the test that I'm not seeing?

asked Jan 26, 2015 at 2:51
6
  • 6
    Your test is flawed. It runs mostly on empty arrays. In which case the while condition is faster than a method call. Commented Jan 26, 2015 at 2:55
  • For the curious on how I found this: chat.stackoverflow.com/transcript/message/21166582#21166582 Commented Jan 26, 2015 at 2:56
  • Well, @Aaditmshah has been fooled by his own test results... Commented Jan 26, 2015 at 3:00
  • 1
    how come the array is empty ? Commented Jan 26, 2015 at 3:03
  • 2
    How about jsperf.com/the-fastest-way-to-truncate-an-array/10 ? Commented Jan 26, 2015 at 3:05

1 Answer 1

8

JsPerf runs each test multiple times per setup. Which means that you only test against the 10000-elements array once, and in the subsequent (very many) runs only have 100 items left in the array.

For that case, the condition of the while loop is super-fast: A single, probably cached, property access and a comparison. All the other test cases call a method or a setter method (which does just this test internally, and maybe more).

A proper test case, like the one created by @zerkms, does use a new array on every iteration - that's the thing you want to test. The relative difference between the solutions will get smaller as more (similar) work is done, but you can still notice trends.
Oh, and of course even these still fall prey to compiler optimisations, so you can never be really sure...

answered Jan 26, 2015 at 3:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.