Signum Function (numbers)

JavaScript performance comparison

Revision 4 of this test case created

Info

Derived from this question on StackOverflow: Number.sign() in JavaScript

Versions of the test: test everythingonly numbersonly 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;
      agg +=sign(1);                  // +1
      agg +=sign(1908235);            // +1
      agg +=sign(-.1e-1);             // -1
      agg +=sign(0);                  //  0
      agg +=sign(0.00000);            //  0
      for (var i=0; i<10000; i++) {
        var rnd = Math.random()*2-1;
        agg +=sign(rnd++);  // ??
        agg +=sign(rnd++);
      }
    }
   
   
    // 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.0 ? 1|0 : 0|0)|0 - (+x < 0.0 ? 1|0 : 0|0)|0; }
   
   
    // 4. Type-safe:
    function sign4 (x) {
        return typeof x == 'number' ? x ? x < 0 ? -1 : 1 : isNaN(x) ? NaN : 0 : NaN;
    }
   
    // 5. The straightforward way
   
    function sign5(x) {
      if (x !== x ) {
          return 0;
       }
       if ( 0 === x ) {
          return 0;
       }
       if (  0 < x  ) {
         return 1;
       }
       return -1;
     }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
1. Obvious
test(sign1)
pending…
1.1. Not So Obvious
test(sign1b)
pending…
2. Elegant
test(sign2)
pending…
3. Artistic
test(sign3)
pending…
4. Safe
test(sign4)
pending…
5. Straightforward
test(sign5)
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:

0 comments

Add a comment