In JavaScript, is it better to do this:
var h = th > ch ? th : ch;
or
var h = Math.max(th, ch);
?
There is no difference in speed.
max method is likely to be slower, but it also may return a different result if one of the arguments is NaN.
The time complexity of comparating two elements is O(m), so the complexity of min() and max() is O(m).
max() starts with a search value of -Infinity , because any other number is going to be greater than -Infinity. Similarly, Math. min() starts with the search value of Infinity : “If no arguments are given, the result is Infinity .
The second seems clearer to me as it's showing intent rather than implementation.
I doubt there very many situations where any performance difference would make any noticable difference and it's probably implementation dependent anyway.
According to this jsperf test, an if statement is the most performant.
http://jsperf.com/math-min-vs-if-condition-vs/2
However, I do agree that Math.max
/Math.min
is more readable.
Here's a JSPerf test which lets you test it on your browser(s):
http://jsperf.com/math-min-vs-if-condition-vs/13
My tests on several browsers indicate that Math.min, the ternary operator and an if statement perform similarly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With