Possible Duplicate:
Does using $this instead of $(this) provide a performance enhancement?
So I am creating a theater like photo gallery that takes up the entire screen, I change the sizes of the divs and Images depending on the window size. So to do this I have been using:
function setSizes()
{
var theaterHeight = $(".theater-wrapper").height();
var theaterWidth = $(".theater-wrapper").width();
}
$(window).on("resize", window, function() {
setSizes();
});
That’s basically what I am doing to select the elements in order to get the dimensions to set the heights and widths and such, however window resize does get a bit laggy, and I do end up having quite a few selectors and changing quite a few divs and images all in this one function, and also sometimes the initial call doesn’t work properly, or vice versa. So my question is would comibining the selectors result in better performance and such?
like:
var $theaterWrapper = $(".theater-wrapper");
var theaterHeight = $theaterWrapper.height();
var theaterWidth = $theaterWrapper.width();
Here’s a JSPerf that you can either use as is or modify to more closely match your specific case:
http://jsperf.com/combined-jquery-selectors
In my browser (Chrome on a Mac), your original version runs about 4% slower than your suggested optimization. On my iPhone using Safari, it’s about 6% slower. But on Firefox on my Mac, it’s a 14% difference.
So it would appear that your proposed improvement is in fact better.