I've built Conway's Game of Life in the browser just using the DOM. Nothing speical, it's been done before. My goal is to optimize it as best as I can. My actual Game of Life code works fine, and is fast enough for my liking. The bottleneck occurs in updating the screen state. With hundreds of thousands or millions of DOM elements on the screen, you can imagine that this can be quite slow (although faster than I first thought). My question is:
Working with upwards of a million DOM elements on the screen at a time, what is the fastest way to iterate through a list of DOM elements and individually change their style?
I'm using a class to keep track of styles, would it be better to dynamically change their style
instead of class
? I'm keeping all these elements in a multidimensional array, would it be better to iterate through another way (the loop itself is not a bottleneck, there are many such loops in my code that run fast enough for me)? I don't really know anything about "reflows" or how the browser renders things when elements change. Could these ideas be leveraged in a way that increases performance?
Here is my current code:
var updateUI = function () {
for (var i = 0; i < width; i++) {
var row = grid[i];
var rowUI = gridUI[i];
for (var j = 0; j < height; j++) {
rowUI[j].className = "b" + row[j];
}
}
}
with the class style being:
.b1 {
background: #000;
}
You can divide the grid into smaller regions and than update style only to elements in regions which are considered 'dirty' (contain at least one changed element compared to previous iteration). That should significantly reduce the amount of operations you need to do in each update UI call, especially when we're talking about millions of elements.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments