Over a million developers have joined DZone.

Speed Up the jQuery Code: Selectors’ Cache

DZone's Guide to

Speed Up the jQuery Code: Selectors’ Cache

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Short Experiment

Here’s a short optimization of a small chunk of jQuery code. The experiment was to increment the number of DOM element access. In this case this was a change of the innerHTML property – using the $.html() method.

I’ve measured the result with the console.time() method and thus I expect correct results for both cases. In the first case I directly call the jQuery selectors’ html() method:

for (var i = 0; i < 10000; i++) {

While in the second case I “cache” it before the loop:

var t = $('#container');
for (var i = 0; i < 10000; i++) {

and here’s the full code in the first case:

<title>jQuery Cache</title>

<div id="container"></div>

<script src="/scripts/library.js"></script>

$(document).ready(function() {

for (var i = 0; i < 10000; i++) {

The Results

As expected the second “cached” approach gave better results. With the increment of the iterations the second method began to be slightly better than the first one. That’s not so much, but imagine you have more than one selector in the loop’s body?


Note that in the time is in ms, and, yes, this is not so much, but when you deal with large data and you’ve more than one selector in the loop’s body, this can be critical!


Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}