Backbone where().length vs count

Benchmark created by redexp on


Preparation HTML

<script src="https://jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="https://jashkenas.github.io/backbone/backbone-min.js"></script>

Setup

Backbone.Model.prototype.matches = function(attrs) {
      return _.matches(attrs)(this.attributes);
    };
    
    Backbone.Model.prototype.equal = function (attrs) {
      for (var key in attrs) {
        if (attrs[key] !== this.get(key)) return false;
      }
      return true;
    };
    
    Backbone.Collection.prototype.where = function(attrs, first) {
      var matches = _.matches(attrs);
      return this[first ? 'find' : 'filter'](function(model) {
        return matches(model.attributes);
      });
    };
    
    Backbone.Collection.prototype.count = function (attrs) {
      var count = 0;
      this.forEach(function (model) {
        if (model.equal(attrs)) count++;
      });
      return count;
    };
    
    Backbone.Collection.prototype.countMatches = function (attrs) {
      var count = 0;
      this.forEach(function (model) {
        if (model.matches(attrs)) count++;
      });
      return count;
    };
    
    var c = new Backbone.Collection();
    
    for (var i = 0; i < 1000; i++) {
      c.add({a: 1, b: 2, c: 3});
    }

Test runner

Ready to run.

Testing in
TestOps/sec
where().length
c.where({a: 1, b: 2, c: 3}).length;
ready
count()
c.count({a: 1, b: 2, c: 3});
ready
countMatches()
c.countMatches({a: 1, b: 2, c: 3});
ready

Revisions

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

  • Revision 1: published by redexp on