Reputation: 4199
I have an array of 10000 objects, and I have to count how many of of the first 500 ones satisfy some conditions. This operation has to be executed several times during an animation.
Which code has a better performance (or is preferable for other reasons) among the following two cases?
Version 1
var el,ct=0;
for (var j=0;j<500;j++) {
el=arr[j];
if (el.a==1 && el.b<8 && el.c>2) ct++;
}
Version 2
var ct=arr.filter(function(el,j){return j<500 && el.a==1 && el.b<8 && el.c>2}).length;
Upvotes: 1
Views: 4397
Reputation: 2785
when you compare the two snippets and just care for performance, then the for loop is more efficient. I have not tried it and benchmarked it myself, but here is a general description of the differences.
In the for loop version, you only "visit" the first 500 elements of the list. the function passed to the filter will always be applied to all elements, doing an additional check for the index of the element being below 500. Just from that fact, that you have more elements to inspect, there's more work to do in the filter case.
Further, there is a general price to be paid when calling a function in any programming language. That is to update the stack (in which function local variables are stored; variables visible in the calling function are not visible in the called function. To ensure that, the stack is used). The for loop stays in the same function, therefore local variables scope does not change, and no stack needs to be updated.
Therefore, from a mere performance point of view, the for loop is preferable.
Nevertheless, I personally find the more functional style (of applying a filter) more elegant, easier to read and maintain. It would need some more adjustments -for example, to create a view on the original array so that not all 10k elements are being visited. I won't go too much in depth here as this is not the original question :)
Upvotes: 4
Reputation: 538
You could use devtools methods such as console.time() in order to bechmark these approaches.
console.time('for-loop approach');
var el,ct=0;
for (var j=0;j<500;j++) {
el=arr[j];
if (el.a==1 && el.b<8 && el.c>2) ct++;
}
console.timeEnd('for-loop approach');
console.time('filter approach');
var ct=arr.filter(function(el,j){return j<500 && el.a==1 && el.b<8 && el.c>2}).length;
console.timeEnd('filter approach');
Upvotes: 1