I have a web-based application which is very highly reliant on jquery / javascript, and its sometimes a bit slow. One of the things that gets done frequently is changes to the grid (jqGrid) which means each time I'm using jQuery to select that object, ie:
function load_editor() { $('#listview').jqGrid(do_stuff); }
I believe simply storing a reference to $('#listview') - since its used in a half dozen functions - would be quicker. So is there any drawback to setting it up like this:
listvi开发者_开发问答ew = $('#listview');
function load_editor() { listview.jqGrid(do_stuff); }
It would seem this way common objects are already in memory, and wont incur the penalty of the lookup on each use. Is there any downside to structuring this way?
( I'm aware in my examples, I'm throwing out a global. Its all nicely encapsulated in an object in the actual project, I just am using these examples to illustrate my point. )
Absolutely you should.
And I strongly recommend you follow the style of the linked article - name your jQuery object variables with a $
prefix. Knowing which of your variables are jQuery objects just by looking at them will be of great help to you when your project becomes large.
There's nothing wrong with it, and in fact it's a great idea in critical code. However, the Sizzle engine is really fast, so you should consider the sort of mess you might be making with lots of such variables and whether the performance benefit is worth it.
Of course if your DOM changes a lot, you need to be careful that what you've got saved remains valid across DOM updates.
精彩评论