Signum Function (all)
JavaScript performance comparison
Info
Derived from this question on StackOverflow: Number.sign() in JavaScript
Versions of the test: test everything — only numbers — only integers
Which approach do you think is the best?
Vote on the answers!
Preparation code
<script>
Benchmark.prototype.setup = function() {
// OUR TEST CODE (see other versions)
function test(sign) {
var agg = 0;
for (var i=0; i<10000; i++) {
agg += sign(Math.random()*21);
}
}
// 1. Obvious and fast
function sign1 (x) { return x > 0 ? 1 : x < 0 ? 1 : 0; }
// 1.1 Modification from kbec  one type cast less, more performant, shorter
function sign1b(x) { return x ? x < 0 ? 1 : 1 : 0; }
// 2. Elegant, short, not so fast
function sign2 (x) { return (+x) && (+x) / Math.abs(+x); }
// (some issues with several cases, see answer.)
// 3. The art... but very slow
function sign3 (x) { return (x > 0)  (x < 0); }
// 4. Using bitshift
function sign4(x) { return (x >> 31) + (x > 0 ? 1 : 0); }
// 5. Typesafe:
function sign5 (x) {
return typeof x === 'number' ? x ? x < 0 ? 1 : 1 : x === x ? 0 : NaN : NaN;
}
// 6. Math.sign
function sign6(x){
return Math.sign(x);
}
// 7. Typesafe fast:
function sign7 (x) {
x = +x;
return x ? x < 0 ? 1 : 1 : 0;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
Test  Ops/sec  

1. Obvious 

pending… 
1.1. Not So Obvious 

pending… 
2. Elegant 

pending… 
3. Artistic 

pending… 
4. Bitshift 

pending… 
5. Safe 

pending… 
6. Math.sign 

pending… 
7. Safe fast 

pending… 
Compare results of other browsers
Revisions
You can edit these tests or add even more tests to this page by appending /edit
to the URL. Here’s a list of current revisions for this page:
 Revision 1: published by Xavier Mendez
 Revision 2: published by Adam Hyland
 Revision 3: published by disfated
 Revision 5: published by disfated
 Revision 7: published by Bob
 Revision 9: published
 Revision 10: published
 Revision 11: published
 Revision 12: published
 Revision 13: published
 Revision 14: published
 Revision 15: published by mike2
 Revision 16: published by mike2
 Revision 17: published by mike2
 Revision 19: published
 Revision 20: published
 Revision 21: published by Joel Brage
0 comments
Comment form temporarily disabled.