Comparisons on emulated tagged unions

JavaScript performance comparison

Test case created by sorella

Info

The different ways of emulating tagged union types in JS.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // Numeric comparisons
    var EitherN = {
      left: 0, right: 2
    }
   
    // Identity comparisons 1 (bonus: actually have the type name)
    var EitherI = {
      left: ['left'], right: ['right']
    }
   
    // Identity comparisons 2
    var EitherI2 = {
      left: {}, right: {}
    }
   
    // Instance comparisons
    var EitherC = function(){}
    EitherC.left = function(){
                     function Left(){}
                     Left.prototype = new EitherC
                     return new Left
                   }
   
    EitherC.right = function (){
                      function Right(){}
                      Right.prototype = new EitherC
                      return new Right
                    }
                   
   
    // Baseline
    var Baseline = {}
    Baseline.left = false
    Baseline.right = true
    Baseline.no = null
   
    // Side-effect catch-all so we avoid the possibility of JITs being too smart
    var r
};
</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
Numeric tags
var x = EitherN.left
var y = EitherN.right
if      (x === EitherN.left){ r = 1 }
else if (y !== EitherN.right){ r = 2 }
else if (x === EitherN){ r = 3 }
pending…
Identity tags (array)
var x = EitherI.left
var y = EitherI.right
if      (x === EitherI.left){ r = 1 }
else if (y !== EitherI.right){ r = 2 }
else if (x === EitherI){ r = 3 }
pending…
Identity tags (object)
var x = EitherI2.left
var y = EitherI2.right
if      (x === EitherI2.left){ r = 1 }
else if (y !== EitherI2.right){ r = 2 }
else if (x === EitherI2){ r = 3 }
pending…
Instance tags
var x = EitherC.left
var y = EitherC.right
if      (x === EitherC.left){ r = 1 }
else if (y !== EitherC.right){ r = 2 }
else if (x === EitherC){ r = 3 }
pending…
Boolean baseline
var x = Baseline.left
var y = Baseline.right
if      (x === Baseline.left){ r = 1 }
else if (y !== Baseline.right){ r = 2 }
else if (x === Baseline.no){ r = 3 }
pending…
Boolean baseline (truthy test)
var x = Baseline.left
var y = Baseline.right
if      (x != null){ r = 1 }
else if (!y){ r = 2 }
else if (x == null){ r = 3 }
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment