Stopper
Stopper

Reputation: 411

What is faster for or each?

I have an AJAX + jQuery example, where on success I have my data array. For my experiment in Firebug, I didn't see much difference. Which is faster, for or each in jQuery?

for example:

for (var i = 0; i < data.length; i++) {
    options += '<option value="' + data[i].c_id + '">'+ data[i].c_name +'</option>';
}

each example:

$(data).each(function() {
    options += '<option value="' + $(this).attr('c_id') + '">' + $(this).attr('c_name') + '</option>';
});

Upvotes: 2

Views: 715

Answers (2)

pranky64
pranky64

Reputation: 415

In this case for loop would definetly be faster. You would generally prefer using the .each() of jquery when iterating over the html tags in your page. Jquery may not always be faster than core javasript, but its definetly much more cleaner and developer friendly ;)

Upvotes: 7

Anoop
Anoop

Reputation: 23208

definitely for loop is faster. but there will be very small difference. it only make difference if you have very large data.

Upvotes: 2

Related Questions