For example, if I wanted to set all negative integers in an array to 0, which code is more commonly used or is faster?
int[] arr = {1, -2, -3, 4, -5};
for (int i = 0; i < arr.length; i++){
if (arr[i] < 0){
arr[i] = 0;
}
}
OR
int[] arr = {1, -2, -3, 4, -5};
for (int i = 0; i < arr.length; i++){
arr[i] = Math.max(arr[i], 0);
}
I find I use the first one more often.
Faster approach deppends on the language, but IMO I always choose readability over perfomance (in some cases, perfomance is crucial, so in this case, you go to the most perfomatic way).
Said that, I prefer the first example:
int[] arr = {1, -2, -3, 4, -5};
for (int i = 0; i < arr.length; i++){
if (arr[i] < 0){
arr[i] = 0;
}
}
It's easier to read and best to maintain this code, than the second example, but again, it's my opinion.
But, the first example can be done in different, deppendign on the language of you choose, like Javascript, you can do this in one line:
let array = [-1 -2, -3, 4, -5];
let arrayMaped = array.map(item => item >= 0 ? item : 0);
console.log(arrayMaped);