Signum Function (all)

JavaScript performance comparison

Revision 9 of this test case created by

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()*2-1);
    }
  }
  
  
  // 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 bit-shift
  function sign4(x) { return (x >> 31) + (x > 0 ? 1 : 0); }
  
  // 5. Type-safe:
  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. Type-safe 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.

Testing in CCBot 2.0.0 / Other 0.0.0
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. Bit-shift
test(sign4)
pending…
5. Safe
test(sign5)
pending…
6. Math.sign
test(sign6)
pending…
7. Safe fast
test(sign7)
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.

0 Comments