Reputation:
I am new into Javascript and for the purposes of a simple game, I need to display a 200x200 grid on a page, with each cell containing a boolean value. My current approach looks like this: I create an HTML table dynamically, assign IDs and add a checkbox on each cell.
Here is how I go about creating my table:
const a = 200;
var resultTable = '<table name = "mytab" id = "abc">';
for (var i = 0; i < a; i++) {
resultTable += '<tr>';
for (var j = 0; j < a; j++) {
var uid = i + '.' + j;
resultTable += '<td class="container"><input type="checkbox" id="'
+ uid + '" class="regular-checkbox"><\/td>';
}
}
and this is how I am collecting values:
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
var yy = i + '.' + j;
/* if (document.getElementById(yy).checked) do something */
}
}
It works but there are some serious performance issues. Is there a different approach of doing this faster? Any help is appreciated.
Upvotes: 1
Views: 126
Reputation: 20944
A performance enhancement would be selecting the elements. Currently you create the entire table from a string and later select each input with document.getElementById()
. You could improve this by creating a reference to each input when you create the elements, so you don't have to find it later on.
With document.createElement()
you can create instances of elements in JavaScript. The function returns a reference to the created element which you can store to use later on.
For example, you could create an input element with it.
const input = document.createElement('input');
input.type = 'checkbox';
input.checked = true;
Now you have an input element already saved in the input
constant. Now you don't have the find the element later on as you already have a reference to it, making the loop having to do 1 less task per input, resulting in 200 x 200 less tasks.
The example below uses the aforementioned createElement
method to create a <table>
element. In the second loop the <input>
element is created and a reference to the element is stored in an array. Looping through this array is now n(0) which allows you to loop through each input in a single loop.
const amount = 200;
const inputCollection = [];
const table = document.createElement('table');
table.name = 'mytab';
table.id = 'abc';
for (let i = 0; i < amount.length; i++) {
const row = table.insertRow();
for (let j = 0; j < amount.length; j++) {
const input = document.createElement('input');
input.classList.add('regular-checkbox');
input.type = 'checkbox';
// Add the input reference to the collection.
inputCollection.push(input);
const cell = row.insertCell();
cell.append(input);
}
}
document.body.append(table);
inputCollection.forEach(input => {
if (input.checked) {
// Do something.
}
});
Upvotes: 0