Skip to content

Instantly share code, notes, and snippets.

@dustinsenos
Created November 13, 2010 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinsenos/675668 to your computer and use it in GitHub Desktop.
Save dustinsenos/675668 to your computer and use it in GitHub Desktop.
/* Example 1 - Store as variable */
var leftImg = $(images[0]);
var centerImg = $(images[1]);
var rightImg = $(images[2]);
leftImg.css('left', -leftImg.width() + X_OFFSET);
centerImg.css('left', ((windowWidth / 2) - (centerImg.width() / 2)));
rightImg.css('left', windowWidth - X_OFFSET);
/* Example 2 - Lookup */
$(images[0]).css('left', -$(images[0]).width() + X_OFFSET);
$(images[1]).css('left', ((windowWidth / 2) - ($(images[1]).width() / 2)));
$(images[2]).css('left', windowWidth - X_OFFSET);
@dustinsenos
Copy link
Author

The code above runs within the window.resize event. As this is called continuously (in safari at least) while the window is resized I want to make sure it's as quick as possible. Is it faster to grab the elements with the $ selector once (top example) or grab them multiple times. I'm assuming the top example is quicker due to the (I would assume) relatively expensive $(); selector.

@paulirish
Copy link

yup.. first is definitely faster (assuming those assignments are done outside of the resize handler..
you're just setting style.left = stuff + 'px'; so it might be worthwhile to make it generic JS.. shrug.

@dustinsenos
Copy link
Author

Thanks for the reply Paul, glad to get a reply from someone close to the code. The jQuery hammer was blurring my vision – switched everything to style.left

@paulirish
Copy link

in general though it's pretty damn fast.. and usually i dont like recommending going to plain js for performance... but here it'll look so damn similar and readable still.. so it seems worth it. :)

@dustinsenos
Copy link
Author

Makes sense, I think mixing the two too much could drive your code into some strange patterns with no good cause. I'm incredibly interested in the performance side of JS / jQuery so I appreciate your insight.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment