Reputation: 15435
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?
Upvotes: 4
Views: 2139
Reputation: 665030
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…
Upvotes: 8