Reputation: 392
I am facing issue with iterating list of records, it's taking too much time to load the data on the screen, due to this performance is getting down.
I tried the following scenarios.
<select class="append"/>
var listOfrecords = [{"name":"hello"},{},{}......etc];//assume 3800 records
using forEach
=======================
listOfrecords.forEach(function(index,record){
//I tried both
$(".append").append('<option>'+record.name+'</option>');
or
$(".append").html('<option>'+record.name+'</option>');
})
using for loop
=====================
for(var int i=0;i<=listOfrecords.length;i++){
//I tried both
$(".append").append('<option>'+listOfrecords[i].name+'</option>');
or
$(".append").html('<option>'+listOfrecords[i].name+'</option>');
}
using while loop
===================
var i = listOfrecords.length;
while(i--){
//I tried both
$(".append").append('<option>'+listOfrecords[i].name+'</option>');
or
$(".append").html('<option>'+listOfrecords[i].name+'</option>');
}
using for in
============
for(var i in listOfrecords){
//I tried both
$(".append").append('<option>'+listOfrecords[i].name+'</option>');
or
$(".append").html('<option>'+listOfrecords[i].name+'</option>');
}
The data is displayed on the screen, but it takes too much time. Can anyone suggest me, is there any way to render the data faster.
Upvotes: 0
Views: 80
Reputation: 2350
Accessing the DOM is expensive - you're essentially telling the browser to traverse the DOM tree with every "append", and then insert another element. So each time you access the dom, you're making your bit of code exponentially more expensive to run. Since you're using a loop and accessing the DOM tree 3800 times, I can see why your browser would complain.
A better thing to do is to build an HTML string or DocumentFragment as you don't need to access the DOM with every item in your array.
var string = '';
for ( var i = 0, i < elements.length, i++ ) {
string += '<option>' + elements.content + '</option>';
}
$('body').append(string);
Upvotes: 1
Reputation: 177
You can iterate and add values on a string, and then just call .append
once.
It's much quicker, with an approximately 9-10x speed increase
var listOfrecords = [{"name":"hello"},{},{}......etc];//assume 3800 records
var newOptions = '';
listOfrecords.forEach(function(index,record){
newOptions += '<option>'+record.name+'</option>';
});
$(".append").append(newOptions); //only having to call append insert once
<select class="append"/>
Font: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly
Upvotes: 0