regex vs slice

JavaScript performance comparison

Revision 16 of this test case created by mauk

Preparation code

<script>
  var toTypeRegExp = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1];
      }
      
  var toTypeSlice = function(obj) {
      return ({}).toString.call(obj).slice(8, -1);
      }
      
  var toTypeSliceProto = function(obj) {
      return Object.prototype.toString.call(obj).slice(8, -1);
      }
      
  var oproto = Object.prototype.toString;
  var toTypeSliceCachedProto = function(obj) {
      return oproto.call(obj).slice(8, -1);
      }

  var map = {
          '[object String]': 'String',
          '[object Number]': 'Number',
          '[object Object]': 'Object',
          '[object Array]': 'Array',
          // etc
          };

  var toTypeHashed = function(obj) {
      return map[oproto.call(obj)];
      };

  var toTypeIfs = function(obj) {
      var t = typeof(obj);
      if (t === 'string') return 'String'
      if (t === 'number') return 'Number'

      t = oproto.call(obj);
      if (t === '[object Object]') return 'Object'
      if (t === '[object Array]') return 'Array'
      return "etc...";
      };

  var teststuff = [ [1,2], 'Array', {a:1}, "Object", 1, "Number", "Abc", "String" ];

  var runtest = function(f) {
      for (var i=0; i<teststuff.length; i+=2) {
        if (f(teststuff[i]) !== teststuff[i+1])
           throw i+": "+ teststuff[i]+" got "+f(teststuff[i])+", expected "+teststuff[i+1];
      }
  };
</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
hash lookup, string literals
runtest(toTypeHashed)
pending…
slice (literal)
runtest(toTypeSlice)
pending…
slice (proto)
runtest(toTypeSliceProto)
pending…
slice (cached proto)
runtest(toTypeSliceCachedProto)
pending…
regex
runtest(toTypeRegExp)
pending…
ifs
runtest(toTypeIfs)
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