Seems obvious, but let's say we have 2 arrays and I want to push some objects inside if certain condition is true. Generally speaking, it would be better like this:
let arr1 = [];
let arr2 = [];
if(someCond){
for(let i=0;i<5;i++){
arr1.push(i)
}
}
else{
for(let i=0;i<5;i++){
arr2.push(i)
}
}
or like this:
let arr1 = [];
let arr2 = [];
for(let i=0;i<5;i++){
if(cond) arr1.push(i)
else arr2.push(i)
}
I think the second option looks shorter, but maybe it's worse in performance.
The best is:
const arr1 = [];
const arr2 = [];
const cond = Math.random() > 0.5;
const arr = cond ? arr1 : arr2;
for(let i = 0; i < 5; ++i){
arr.push(i);
}
console.log('arr1', arr1);
console.log('arr2', arr2);
Better to execute the loop one time than the length of array so this is the better of your options
if(someCond){
for(let i=0;i<5;i++){
arr1.push(i)
}
}
else{
for(let i=0;i<5;i++){
arr2.push(i)
}
}
Because you only execute the conditional one time then..
As the path of processing this code, i get the following
For every item in the array, i must check the condition
Or no the first option, for this condition, i must do this, otherwise, do that to every item.
The first option, is better in performance, but, unless you're working with BigData i don't think this will influence the processing at all as both are simple instructions to be processed.
This of course depends on the number of itens you're looping and on the complexity of the conditional.
If you use a function in the condition, it'll use more memory, so the first option will be better.
If your condition is simples and your items collection not too large, you are free to use any without problems.