Cast booleans

JavaScript performance comparison

Revision 4 of this test case created by Mike

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var t = 'true', T = 'TRUE', f = 'false', F = 'FALSE';
  
  var jsonize = function(s){
    return JSON.parse(s.toLowerCase());
  };
  String.prototype.bool = function() {
      return (/^true$/i).test(this);
  };
  var proto = function(s){
    return s.bool();
  };
  var equalize = function(s){
    return (s.toLowerCase() === 'true');
  }
  Boolean.parse = function (str) {
    switch (str.toLowerCase ()) {
      case "true":
      case 1:
        return true;
      case "false":
      case 0:
        return false;
    }
  };
  var parser = function(s){
    return Boolean.parse(s);
  };
  
  var parser2 = function (value){
      if (typeof(value) == 'string'){
          value = value.toLowerCase();
      }
      switch(value){
          case true:
          case "true":
          case 1:
          case "1":
          case "on":
          case "yes":
              return true;
          default: 
              return false;
      }
  };
  
  var universal = function(s){
  var num = +s;
      return !isNaN(num) ? !!num : !!String(s).toLowerCase().replace(!!0,'');
  }
  
  var test = function(fu){
    fu(t); fu(T); fu(f); fu(F);
  };

};
</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
jsonize
test(jsonize);
pending…
proto
test(proto);
pending…
equalize
test(equalize);
pending…
parser
test(parser);
pending…
parser2
test(parser2);
pending…
universal
test(universal);
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