typeof

JavaScript performance comparison

Revision 7 of this test case created

Info

some bench about grabbing types

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var typeCache = {},
          typeString = typeCache.toString,
          typeRegexp = /\w+(?=])/;
     function _typeOf(obj) {
        var type = typeString.call(obj);
        return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase());
      }
   
    var typeObj = {};
   
    function typeOf1(obj) {
      return typeObj.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
    }
   
    var re = /\s([a-zA-Z]+)/;
    function typeOf2(obj) {
      return typeObj.toString.call(obj).match(re)[1].toLowerCase();
    }
   
    var re2 = /\w+(?=])/;
    function typeOf3(obj) {
      return re2.test(typeObj.toString.call(obj)) &&
             RegExp.lastMatch.toLowerCase();
    }
   
    var typeOf4 = (function(Object, RegExp){
      // https://gist.github.com/WebReflection/6323064
      var toString = Object.prototype.toString,
          cache = (Object.create || Object)(null),
          matchClass = /\w+(?=])/;
      return function typeOf(Unknown) {
        var asString = typeof Unknown;
        return asString == 'object' ? (
          Unknown === null ? 'null' : (
            cache[asString = toString.call(Unknown)] || (
              cache[asString] = matchClass.test(asString) &&
                                RegExp.lastMatch.toLowerCase()
            )
          )
        ) : asString;
      };
    }(Object, RegExp));
   
    var result;
};
</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
typeOf1
for(var
  i = 0,
  list = [
    i, null, undefined, false, '',
    {}, new Date, Function
  ],
  length = list.push(list);
  i < length; result = typeOf1(list[i++])
);
pending…
typeOf2
for(var
  i = 0,
  list = [
    i, null, undefined, false, '',
    {}, new Date, Function
  ],
  length = list.push(list);
  i < length; result = typeOf2(list[i++])
);
pending…
typeOf3
for(var
  i = 0,
  list = [
    i, null, undefined, false, '',
    {}, new Date, Function
  ],
  length = list.push(list);
  i < length; result = typeOf3(list[i++])
);
pending…
typeOf4
for(var
  i = 0,
  list = [
    i, null, undefined, false, '',
    {}, new Date, Function
  ],
  length = list.push(list);
  i < length; result = typeOf4(list[i++])
);
pending…
_typeOf
for(var
  i = 0,
  list = [
    i, null, undefined, false, '',
    {}, new Date, Function
  ],
  length = list.push(list);
  i < length; result = _typeOf(list[i++])
);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment