I have 2000 rows of data as follows
<div class="rr cf">
<span>VLKN DR EXP</span>
<span>01046</span>
<span>VELANKANNI</span>
<span>20:30</span>
<span>DADAR</span>
<span>10:00</span>
</div>
On a button click I am checking for text within them and updating the display of each row to block or none. The code that does this is
$('.rr').each(function(){
this.style.display="block";
});
var nodes = $(".rr");
for(var i=0;i < nodes.length; i++) {
// if data found
nodes.get(i).style.display="block";
// else
nodes.get(i).style.display="none";
}
This seems to be possibly very slow. I get chrome alert box as to kill the page.
Any ideas? what optimization can I do here?
Local Variables and Loops
Taken from: http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html
nodes.lengthas a local variable so that the loop doesn’t have to compute it each time.nodes.get(i)into a local variable to save some time if you are accessing that data a lot.each()loop is a bit slower than looping through the set yourself as well. You can see here that there is a clear difference.Very simple example
You’ll see that in my example, I’ve condensed the loop into a
whileloop:Notice that the
whileloop decrementsithrough each iteration. This way wheni = 0, the loop will exit, becausewhile(0)evaluates tofalse.“Chunking” the Array
Have a look at Nick Zakas‘s
chunkmethod defined here, if you need to run the loop in sections to reduce the chance of crashing the browser:Using createDocumentFragment()
Since you are changing the display property of these elements iteratively, the page mush ‘repaint’ the window for each change. If you use
createDocumentFragmentand make all the changes there, then push those to the DOM, you drastically reduce the amount ofrepaintingnecessary.