views:

105

answers:

1

I have this Jquery code that construct a collection of jquery objects. It takes around 600 ms to execute. I want to optimize it:

var tousBt = $('img.boutonReduire');
var stack = $('');
tousBt.each( function() {
    var id = $(this).attr('id');
    stack = stack.add('#table' + id).add('#img' + id);
  });

Do you see something that I can do ? The result has to be a collection of jquery objects.

Edit: I get all the stacks elements and hide them : stack.addClass('hideit'); There is around 125 elements. And $('*').length give around 7100 elements.

+3  A: 

First and foremost, remove the assignment operation inside your iteration function. stack is an instance---there's no need to reassign it:

var tousBt = $('img.boutonReduire');
var stack = $('');
tousBt.each( function() {
    var id = $(this).attr('id');
    stack.add('#table' + id).add('#img' + id);
});

I'd also suggest getting away from jQuery overhead if you're calling add() a tons of times. Here's a version using a lightweight array to accumulate the selectors:

var tousBt = $('img.boutonReduire');
var stack = [];
tousBt.each( function() {
    var id = this.id;
    stack.push('#table' + id);
    stack.push('#img' + id);
});

Then, to get the finalized selector that you can use with jQuery:

var selector = stack.join(','); 
//$(stack.join(','));

Edit: this may seem absolutely retarded, but this might actually be fastest (worth a shot at least):

var tousBt = $('img.boutonReduire');
tousBt.each(function() {
    var id = this.id;
    $('#table' + id).addClass('selected');
    $('#img' + id).addClass('selected');
});
var stack = $('.selected');
brianreavis
Think this "var id = $(this).attr('id');" can be replaced with just "var id = this.id".
Kamarey
Doh, that's a good point. Edited.
brianreavis
Really a good idea. This minimize Jquery utilization. But in my case it does not help. I get a 2000 ms to construct the Jquery object only. FYI: There is 125 elements in the result stack list. I'm surprised by the result though.
Jean-Philippe Martin
Check the edit. How does that run, in comparison?
brianreavis
Another point is to move out of the loop the "addClass('selected')" and run it ones on stack object: stack.addClass('selected');
Kamarey
Well, that'd defeat the purpose of applying the class for mass selection purposes.
brianreavis
Good idea too. Thanks ! The performance is better with 1500 ms. The problem is that selecting by classname do not have a native implementation in the browser (IE) so this is penalizing.Kamarey, thanks for the input, the var id = this.id works and helps a little !
Jean-Philippe Martin
Modified a little bit your solution : var stack = $('table.selected, img.selected');This help a little. The performance drop to 1200 ms. But what is strange is that subsequent call to it now gives 300 ms. Seems that the browser or Jquery is caching the selection.
Jean-Philippe Martin