In my new site, Aud (which you can see my original post on here), I use a lot of javascript, and I wanted it to be very fast. One part that was amazingly slow was the generation of the playlist. The script does an ajax call to the server to get the playlist as JSON, and then turns each song into a table row and appends it to the table in the playlist div. Simple, yes, but if you do it wrong and have a lot of data, it’s very slow. Heres a tip I figured out to help speed up the process:
Instead of using your typical concatenation techniques like this:
var table = "";
for (var i = 0; i < playlist.length; i++) {
table += "<tr><td><strong>Artist: " + artist + " Album: " + album + " Song: " + song + "</td></tr>";
}
$('#table').append(table);
You would do something like this:
var table = [];
for (var i = 0; i < playlist.length; i++) {
table.push(["<tr><td><strong>Artist: ", artist, " Album: ", album, " Song: ", song, "</td></tr>"].join(''));
}
$('#table').append(table.join(''));
Now some people might think, “Well, why not put the .append() inside the loop?”. You really don’t want to do that. It’s very costly in terms of speed, and ends up even slower.
So if you have a lot of appending to strings, try making it an array, and pusing and joining!