Backbone provides options to select models from collections both by ID (a unique identifier attribute assigned to every model) and by index. Which of these is the fastest way to access items from a collection?
Cracking open Backbone.js, I can see that collection.get(id)
(the select-by-ID function) uses a simple object-literal look-up and collection.at(index)
(the select-by-index function) uses a simple array look-up.
from Backbone.js:
collection.get(id):
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
}
collection.at(index):
// Get the model at the given index.
at: function(index) {
return this.models[index];
}
Because of this, the answer to this question should be directly tied to which is faster - array access or object literal access (in this case assuming that .get
is used in its first iteration, where it's sent an ID, and not a model with an ID, or CID on it).