each method, optimizations

JavaScript performance comparison

Revision 2 of this test case created by Matthias Le Brun

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var _toString = {}.toString
      , ARRAY_CLASS = "[object Array]"
   
    function each(obj, fn, thisValue){
      if(!obj) return obj
      if(_toString.call(obj) == ARRAY_CLASS) {
        for(var i = 0; i < obj.length; i++) fn.call(thisValue, obj[i], i, obj)
      } else {
        for(var i in obj) {
          if(obj.hasOwnProperty(i)) {
            fn.call(thisValue, obj[i], i, obj)
          }
        }
      }
      return obj
    }
   
    var _hasOwn = {}.hasOwnProperty
   
    function optimizedEach(obj, fn, thisValue){
      var i = 0, l, callback
      if(!obj) return obj
      callback = typeof thisValue == "undefined" ? fn : function(a,b,c){return fn.call(thisValue,a,b,c)}
      l = obj.length
      if(typeof l == "number") {
        if(!l) return obj
        for(;i < l; i++) if(false === callback(obj[i], i, obj)) return obj
      } else {
        for(i in obj) {
          if(!_hasOwn.call(obj, i)) continue
          if(false === callback(obj[i], i, obj)) return obj
        }
      }
      return obj
    }
   
    var array = [1,2,3,4,5,6,7,8,9,10]
      , args = (function(){return arguments}).apply(null, [1,2,3,4,5,6,7,8,9,10])
      , object = {foo:"bar", bar:"baz",baz:"foo"}
      , emptyObject = Object.create(null)
    emptyObject.foo = "bar"
    emptyObject.bar = "baz"
    emptyObject.baz = "foo"
};
</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
array (each)
each(array, function(item){var a = item})
pending…
array (optimized)
optimizedEach(array, function(item){var a = item})
pending…
arguments (each)
each(args, function(item){var a = item})
pending…
arguments (optimized)
optimizedEach(args, function(item){var a = item})
pending…
array (thisValue, each)
each(array, function(item){var a = item}, {})
pending…
array (thisValue, optimized)
optimizedEach(array, function(item){var a = item}, {})
pending…
object (each)
each(object, function(item){var a = item})
pending…
object (optimized)
optimizedEach(object, function(item){var a = item})
pending…
escape (each)
each(array, function(item, i){if(i>3) return false})
pending…
escape (optimized)
optimizedEach(array, function(item, i){if(i>3) return false})
pending…
object (no inherits, each)
each(emptyObject, function(item){var a = item})
pending…
object (no inherits, optimized)
optimizedEach(emptyObject, function(item){var a = item})
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