Skip to content

Instantly share code, notes, and snippets.

@uhop
Created August 11, 2011 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uhop/1141073 to your computer and use it in GitHub Desktop.
Save uhop/1141073 to your computer and use it in GitHub Desktop.
What's faster: ?:, Math.min(), or Math.max()?
// What's faster: "if", ?:, Math.min(), or Math.max()?
this.group(
"Min/max comparison",
function baseline(){
// this one does nothing, it is here only for comparison
var a = Math.random(), b = Math.random(),
c = a;
},
function if_stmt(){
var a = Math.random(), b = Math.random(),
c = a;
if(c < b){ c = b; }
},
function ternary(){
var a = Math.random(), b = Math.random(),
c = a < b ? a : b;
},
function ternary_assignment(){
var a = Math.random(), b = Math.random(),
c = a;
c = c < b ? c : b;
},
function min(){
var a = Math.random(), b = Math.random(),
c = Math.min(a, b);
},
function max(){
// this one does the opposite, but the speed should be the same as min()
var a = Math.random(), b = Math.random(),
c = Math.max(a, b);
}
);
@uhop
Copy link
Author

uhop commented Aug 11, 2011

Benchmark it with http://www.perfjs.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment