[sum all nums in range] is .sort() less efficient?

Tell us what’s happening:

Does the built-in .sort() method decrease performance? I understand it’s negligible in this case. I read that different browsers handle .sort() in their own way but they all tend to be logarithmic. Is it more efficient to get the minimum and maximum values from the array? Why?


function sumAll(arr) {
    let sum = 0
    arr.sort((a,b) => a-b)
    for(let i = arr[0]; i <= arr[1]; i++) sum += i
    return sum
}

console.log(sumAll([4, 1]))

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36

Challenge: Sum All Numbers in a Range

Link to the challenge:

Using sort vs getting the min and max on an array of two values will have a negligible performance impact. The bigger question is if you really want to mutate the input data.

For this problem, the best performance would come from the formula for the sum of numbers in a range.

1 Like