tags:

views:

212

answers:

4

In JavaScript, is it better to do this:

var h = th > ch ? th : ch;

or

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

?

+6  A: 

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.

John Burton
+1 on that : with Math.max, people reading your code **immeditaly** understand what you are trying to do ; with ?:, they'll have to think at least for one or two seconds... If you have 300 lines of code, it's already a couple of minutes lost thinking with probably no good reason (except in some really critical parts of your application, this kind of micro-optimization is probably pointless) -- who said something about premature optimization, and root of all evil ? ^^
Pascal MARTIN
I think that was donald knuth
Breton
A: 

For speed, there is no significant difference.

For style, Math.max is much more readable and therefore the best option.

JBRWilkinson
A: 

Math.max() acts exactly the same thing you wrote as first. It uses the ternary operator to return the max. So if u want to spare some nanosecond you may use the first way, in order to avoid a call to a function. However, IMHO, this difference cannot really affects performance, unless u have an heap of Math.max to do.

A: 

On mono the JIT can inline Math.Min and Math.Max methods and provide better performance compared to custom, inline, implementations. It will use special instructions if available by the hardware. So one day if in JavaScript there's some JIT (Google V8 ?) probably it will be some performance benefit to user Math class.

Petar Petrov