0

I am using this for loop in some code. This code appends all the elements present in "left array" in a table and assigns a unique rowID to them which is working perfectly fine.

Problem is: This loop takes around 9 seconds to execute when length of "left" array is 5000,but when length of "left" array is 10000 and 15000, it takes 27 seconds and 54 seconds respectively. I guess this is an ambiguous behavior, the time should increase linearly with increase in number of iterations. I would be glad if someone could tell me the reason and the solution to this problem.

Thanks in advance. :)

$("body").append('<p id = "p1">table1</p>')
table = $('<table id="first-table">');
div = $('<div ></div>');
$(div).append(table);
$('body').append(div);

for (var rowID = 0, l = left.length; rowID < l; rowID++) {

    if (left[rowID] != null) {
        var tr = $('<tr>');
        table.append(tr);
        tr.append('<td class="cell" id="a' + rowID + '">' + left[rowID] + '</td>');
    }
}
Satpal
  • 132,252
  • 13
  • 159
  • 168

1 Answers1

2

Appending N elements individually causes up to N reflow's. As the no of elements to be added increases it decreases performance.

You can refactor your code, create the DOM fragment and nodes in memory then use single append()

//Createing Nodes in memory
var table = $('<table id="first-table">');
for (var rowID = 0, l = left.length; rowID < l; rowID++) {
    if (left[rowID] != null) {
        $('<tr>').append('<td class="cell" id="a' + rowID + '">' + left[rowID] + '</td>')
                 .appendTo(table);
    }
}

var div = $('<div ></div>').append(table);
var paragraph = $('<p id = "p1">table1</p>');

//Append to DOM     
$("body").append(paragraph.add(div))

A good read What is DOM reflow?

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Your solution did reduce the time by 1 second but still **did not solve exponential increase** in time with increase in iterations. After using your code, 15k iterations take 50 seconds. :) – Yash Parikh Jan 19 '17 at 10:16
  • @YashParikh, Can you create a fiddle? and try this one `var str = ''; for (var rowID = 0, l = left.length; rowID < l; rowID++) { if (left[rowID] != null) { str += '' + left[rowID] + ''; } } var table = $('', { html: str });` `
    – Satpal Jan 19 '17 at 10:21