Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed and style of Math.max vs ternary operator in JavaScript

Tags:

javascript

In JavaScript, is it better to do this:

var h = th > ch ? th : ch;

or

var h = Math.max(th, ch);

?

like image 853
Josh Gibson Avatar asked Aug 05 '09 10:08

Josh Gibson


People also ask

Are ternary operators faster Javascript?

There is no difference in speed.

Is Max math slower?

max method is likely to be slower, but it also may return a different result if one of the arguments is NaN.

What is the time complexity of math Max?

The time complexity of comparating two elements is O(m), so the complexity of min() and max() is O(m).

Why is math MAX () less than math MIN ()?

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 .


3 Answers

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.

like image 182
jcoder Avatar answered Oct 20 '22 12:10

jcoder


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.

like image 13
Craig A Avatar answered Oct 20 '22 11:10

Craig A


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.

like image 3
Tomasz P. Szynalski Avatar answered Oct 20 '22 12:10

Tomasz P. Szynalski