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.
CodePudding user response:
The best is:
const arr1 = [];
const arr2 = [];
const arr = cond ? arr1 : arr2;
for(let i = 0; i < 5; i){
arr.push(i);
}
CodePudding user response:
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..
CodePudding user response:
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.
CodePudding user response:
Assuming no optimization, the second option does require more computations. So one can infer that the second option is indeed worse in performance. For instance the condition inside the if clause is evaluated for every element of the table and in the worst case it can result in many 'jumps' in the code. If the size of the array is indeed 5, then the effect would be negligible.
Another approach could be the following.
let arr1 = [];
let arr2 = [];
let arr3=someCond?arr1:arr2;
for(let i=0;i<5;i ){
arr3.push(i)
}