Andy
Andy

Reputation: 14575

Do unnecessary for loop iterations affect speed?

I have dynamic HTML with many <div>s that will have a class of groupX where X is a number between 1 and 100. I need to find out how many groups are in use to use elsewhere in the application and have this code at the moment:

for(i = 0; i <= 100; i++){                       
  if($j('.group' + i).size() > 0) {          
    totalAmountOfGroups++; 
  }
} 

It works, though sometimes only 6 groups may be used, so I'm looping through 94 times unnecessarily and was wondering if this would affect speed (especially with the jQuery inside)

Upvotes: 0

Views: 93

Answers (3)

marekful
marekful

Reputation: 15351

It depends on what is executed in the body of the for. The one in the question doesn't seem too pricey. However, I'd go for a different solution. When generating the HTML, you could add another class to the elements without the counter. E.g. class="group group14". This way you could use a selector $('.group') so you would only iterate through the elements you need to.

Upvotes: 3

Silver_Clash
Silver_Clash

Reputation: 405

Try like this

It's not a good way, but faster than you approach. The best way is mark all elements by class 'group', and store group number in data attribute like data-group="n". After this you can select all elements by one operation, and than iterate selected elements to extract group number from attribute.

Upvotes: 2

Alen Genzić
Alen Genzić

Reputation: 1418

You could add another class to your group , lets call it grouped, and then filter through them using a regex

var total = 0;
total = $('.grouped').filter(function(){
    return $(this).attr('class').match(/group[d+]/g);
}).size();

Upvotes: 1

Related Questions