Backbone's collection comparator: sort attribute vs. sort function

Benchmark created by Igor Petrov on


Description

Which way to sort collection is faster?

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>

Setup

var collection = new Backbone.Collection(),
    order = new Array(100000),
    models = [];
    
    _.each(order, function (item, index) {
    models.push({
    order: (item % 2 === 0) ? 2 : 1,
    index: index
    });
    });

Test runner

Ready to run.

Testing in
TestOps/sec
Sort attribute
collection.comparator = function (model) {
var denominator = 1000000;
return [model.get('order') / denominator , model.get('index') / denominator ];
};

collection.add(models);
ready
Sort function
collection.comparator = function (a, b) {
var orderA = a.get('order'),
orderB = b.get('order'),
indexA = a.get('index'),
indexB = b.get('index');

if (orderA > orderB) {
return 1;
} else if (orderA < orderB) {
return -1;
}

return indexB - indexA;
};

collection.add(models);
ready

Revisions

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

  • Revision 1: published by Igor Petrov on