backbone.js - Iterating Through Collections in BackboneJs, is for faster than forEach? -


iterating through collections: although can use simple loop iterate through collection follows:

//a simple loop for(var = 0; < mylibrary.length; i++){ var model = mylibrary.at(i); console.log('book ' + + ' called ' + model.get('name')); } 

there more elegant utility function provided underscore helps iterate through collections, namely, foreach function.

//using foreach mylibrary.foreach(function(model){ console.log('book called ' + model.get('name')); }); 

which 1 better performance-wise

if @ underscore source can see tests native foreach , chooses on using loop. given 2 options, on browsers support native foreach, underscore faster, , have same run time in others.

var each = _.each = _.foreach = function(obj, iterator, context) {     if (obj == null) return obj;     if (nativeforeach && obj.foreach === nativeforeach) {       obj.foreach(iterator, context);     } else if (obj.length === +obj.length) {       (var = 0, length = obj.length; < length; i++) {         if (iterator.call(context, obj[i], i, obj) === breaker) return;       }     } else {       var keys = _.keys(obj);       (var = 0, length = keys.length; < length; i++) {         if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;       }     }     return obj;   }; 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -