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?
-
6Your test is flawed. It runs mostly on empty arrays. In which case the while condition is faster than a method call.Bergi– Bergi2015年01月26日 02:55:32 +00:00Commented Jan 26, 2015 at 2:55
-
For the curious on how I found this: chat.stackoverflow.com/transcript/message/21166582#21166582jdphenix– jdphenix2015年01月26日 02:56:47 +00:00Commented Jan 26, 2015 at 2:56
-
Well, @Aaditmshah has been fooled by his own test results...Bergi– Bergi2015年01月26日 03:00:42 +00:00Commented Jan 26, 2015 at 3:00
-
1how come the array is empty ?user1428716– user14287162015年01月26日 03:03:55 +00:00Commented Jan 26, 2015 at 3:03
-
2How about jsperf.com/the-fastest-way-to-truncate-an-array/10 ?zerkms– zerkms2015年01月26日 03:05:25 +00:00Commented Jan 26, 2015 at 3:05
1 Answer 1
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...
Explore related questions
See similar questions with these tags.