Reputation: 315
Which way will be faster and use less memory?
For now i have rendered dynamic <table>
by jQuery. Sometimes it has around few thousand cells and it is working so slowly when i do events on it. Html2Canvas is taking alot time to render this table as image. So i wonder about use interactive canvas.
Here is fiddle with script for generating table http://fiddle.jshell.net/j6G66/
Upvotes: 3
Views: 2278
Reputation: 206209
I created two examples,
One that mirrors the way you're creating your table
and that's by creating and appending jQuery object elements on every loop iteration:
function createDynamicTable(rows, cols) {
var table = $('<table />');
for(var i=0; i<rows; i++){ // noprotect
var row = $('<tr />');
for(var j=0; j<cols; j++){
var cell = $('<td />');
cell.text("R"+i+"-C"+j);
cell.appendTo( row ); // Appends here....
}
row.appendTo( table ); // Appends here....
}
$('#tableContainer').append( table ); // Appends here....
}
The second one uses a different way of creating a table, that is based instead on the principle of
concatenating a HTML String representation of the needed elements:
function createDynamicTable(rows, cols) {
var table = "<table>";
for(var i=0; i<rows; i++){
var row = "<tr>";
for(var j=0; j<cols; j++){
var cell = "<td>R"+i+"-C"+j+"</td>";
row += cell;
}
row += "</tr>";
table += row;
}
table += "</table>"
$('#tableContainer').append( table ); // Append only once!
}
Now let's be humans and exaggerate a bit creating a table with 1000 rows and 10 cells in each running:
var start = new Date().getTime();
createDynamicTable(1000, 10);
var total = new Date().getTime() - start;
And let's see the results:
IN-LOOP jQuery OBJECTS/EL. CREATION vs. IN-LOOP STRING CONCATENATION
~920 ms ~130 ms
A (logical) side-note on the string concatenation:
you'll not be able to keep copies of alive Objects inside data-*
attributes like i.e:
cell = "<td data-objectcopy='"+ myObject +"'>...</td>"
cause the object will result in String "[object Object]"
, in contrast to jQuery's .data()
:
cell = $("<td />", {html:"..."}).data("objectcopy", myObject );
where any further change to the object like: $(td).eq(0).data().objectcopy.someProperty = "new value";
will keep it's reference to the original myObject
object alive.
Upvotes: 4