views:

187

answers:

1

I have a big jQuery code and I am thinking at speed performance of my functions. When an element is clicked (mousedown) i need to assign an image as background. I can do this by 2 ways:

$('#element li.class').css({"background":"someimageURL"});

or

$('#element li.class').addClass("someclass");

where "someclass" have the actual CSS background image. Witch function works better in this case.

Is there a way to test various functions speed?

Thank you

+4  A: 

I'm almost certain .addClass() would be the faster of the two. This involves essentially tacking on another classname to the element, whereas the alternative would require iterating through the elements styles and setting many explicit rules.

Setting a couple css rules via $.css() is likely nothing to worry about, but if you find yourself setting many, often, it's time to create a class and apply/remove that as needed.

I've extracted the logic of both methods into a single location for you to review if you like.

http://pastie.org/842738

Jonathan Sampson
Also not speed/performance related, it's a lot easier to change a CSS class than JS source code for changing a style later on ;)
henasraf
The implementation of "addClass" isn't as fancy as I would have thought. It does a lot of re-scanning of the class string when adding multiple classes. For short className values that's probably not a problem.
Pointy
Thanx Jhonathan. I will look at your link. I also think that addClass is faster.
Mircea