Vivek Chandra
Vivek Chandra

Reputation: 4358

Chaining vs creating a new Collection - efficiency

I'm a beginner in Backbone and want to know which among the 2 is more efficient and the expected way of doing things.

Type A : Creating a new collection which accepts result from earlier operation and plucking a key from the new collection

result = new Backbone.Collection(this.collection.where({"x":y})).pluck("z")

OR

Type B : Chaining feature of collections - Array from filter and map.

result = this.collection.chain()
        .filter(function(model){model.get("x")===y)
        .map(function(model){model.get("z")})
        .value()

Upvotes: 0

Views: 44

Answers (1)

nikoshr
nikoshr

Reputation: 33364

Benchmarking is the key : chaining wins hands down1 and is clearer2. See http://jsperf.com/backbone-chaining-vs-new-collection for the comparison3.

Of course, if you're really concerned with speed, you would ditch the middle men and use vanilla JavaScript (this could be further optimized, look up array traversing techniques)

var i, l, result = [];
for (i=0, l=this.collection.length; i<l; i++) {
    if (this.collection.models[i].get('x') === y)
        result.push(this.collection.models[i].get('z'));
}

1 Subject to your exact setup/data sample/speed of the wind
2 Note that your filter and map functions miss a return
3 Tests used : http://jsfiddle.net/nikoshr/cek502wp/

Upvotes: 2

Related Questions