mardi 19 novembre 2019

Is maximum/minimum method more conventional than If statements to set a lower/higher bound for values?

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.

Aucun commentaire:

Enregistrer un commentaire