jQuery.each() 和原生JS的for loop效率对比

# Sent: Thursday, March 26, 2015 1:51 PM

Subject: jquery each vs for loop

在看前端代码的时候,看到不少地方都有用到jQuery.each() 方法,我昨天写的reuse lib enhancement的时候也有用到它,好奇jQuery.each() 和原生JS的for loop效率,找到一个对比,看起来原生for loop执行效率要高更多,于是我就refactor 为了原生for loop :)

出处: https://jsperf.com/browser-diet-jquery-each-vs-for-loop

[图片]

jQuery.each() 和原生JS的for loop效率对比

```JavaScript

sap.cus.crm.lib.reuse.controls.Note.prototype._getDefaultNoteTypeId = function() {

var defaultNoteTypeId = "",

noteTypes = this.getModel().getProperty(this.getProperty("noteTypes"));

// second iteration with for loops

// console.time('start of for loop with caching');

for (var i = 0, len = noteTypes.length; i < len; i ++) {

if (noteTypes[i]["DefaultNoteType"]) {

defaultNoteTypeId = noteTypes[i]["TextObjectID"];

return defaultNoteTypeId;

}

}

// console.timeEnd('end of for loop');

/* first iteration with jQuery.each()

jQuery.each(noteTypes,

jQuery.proxy(function(index){

var sPrefix = this.getProperty("noteTypes") + "/" + index; // /NoteTypes/0

var isDefault = this.getModel().getProperty(sPrefix + "/" +

this.getProperty("noteTypeDefaultFlag")); // /NoteTypes/0/DefaultNoteType

if (isDefault) {

defaultNoteTypeId = this.getModel().getProperty(sPrefix + "/" +

this.getProperty("noteTypeId"));

return false;

}

}, this));

*/

// return defaultNoteTypeId;

};

```

加入我们

热门文章