null vs option

Benchmark created by Daniel on


Setup

function helloOrNull() {
      if (Math.random() > 0.5) {
        return null;
      } else {
        return "hello";
      }
    }
    
    function Opt(value) {
      this.value = value;
    };
    
    Opt.prototype.isDefined = function() {
      return !!this.value;
    };
    
      Opt.prototype.map = function(fn) {
        if (this.isDefined()) {
          return new Opt(fn(this.value));
        } else {
          return this;
        }
      };
    
      Opt.prototype.flatMap = function(fn) {
        if (this.isDefined()) {
          return fn(this.value);
        } else {
          return this;
        }
      };
    
      Opt.prototype.getOrElse = function(fn) {
        if (this.isDefined()) {
          return this.value;
        } else {
          return fn();
        }
      };
    
    function helloOpt() {
      if (Math.random() > 0.5) {
        return new Opt(null);
      } else {
        return new Opt("hello");
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
null
var value = helloOrNull();
if (value === null) {
  console.log("nothing");
} else {
  console.log("something");
}
ready
Option
var valueOpt = helloOpt();
var result = valueOpt
  .map(function(value) {
    return "something";
  })
  .getOrElse(function() {
    return "nothing"
  });
console.log(result);
ready

Revisions

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

  • Revision 1: published by Daniel on