Code Optimization

Interesting things about software development and code optimization

Javascript and jQuery - creating a lot of elements like a big grid


Hello dear friends,


Last time I did create a big grid using jQuery and Javascript, and faced with the performance problem.




My task was to create a big calendar grid that should have 20 rows at least and 180 columns (each column for each day for the 6 month period). While developing this grid I had noticed that Microsoft Edge and FireFox browsers hung during this creation cycle for a few seconds (Google Chrome seemed much better). My first method did create each cell for every column and row.

So how to optimize this? I did some googling and found a suggestion to use setTimeout function to avoid browser hanging, but it didn't help a lot in my case. Ugh! What should I do with it. Just in case, here is the piece of code I used to create my grid:

.....

var row, cell;

for(var r=0;r<20;r++)

{

    row = $("<div class='row'></div>");

    for(var i=0; i<180;i++)

    {

         cell = $("<div class='cell'></div>");

         ..........

        row.append(cell);

    }

    ....

    grid.append(row);

}


So, looks pretty simple? I was thinking for a few days on it trying to understand what could I do with it.

At some point I just had thought "what if create one row only and then just clone it as much as needed?". And yes, I was completely right! :) it did reduce time from 4-5 seconds to less than 1 second:

.....
var row, cell;


{
    row = $("<div class='row'></div>");

    for(var i=0; i<180;i++)
    {
         cell = $("<div class='cell'></div>");
         ..........
        row.append(cell);
    }
    ....
    grid.append(row);
}

for (var c = 1; c < 20; c++) {
   grid.append(row.clone(false).off());
}

So now its clear that the clone method grid.append(row.clone(false).off()); much much faster than creating a new elements.



Thank you and see you next time :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y