且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-13 11:59:19

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

[图片]

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;
};