regex vs slice (v10)

Revision 10 of this benchmark created by mauk on


Description

It is not important to get fast results, but to make it fast to use. So I added some code that calls the functions and to make life harder for V8 by supplying different types.

The returned string needs to be compared byte-for-byte. This new version returns a string constant, which is faster because they compare-by-reference.

The hash lookup should also be fast because the returned '[object Object]' strings are internally cached literals. However, it isn't.

Preparation HTML

<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 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

Ready to run.

Testing in
TestOps/sec
hash lookup, string literals
runtest(toTypeHashed)
ready
slice (literal)
runtest(toTypeSlice)
ready
slice (proto)
runtest(toTypeSliceProto)
ready
slice (cached proto)
runtest(toTypeSliceCachedProto)
ready
regex
runtest(toTypeRegExp)
ready

Revisions

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