Notes // jQuery.append() is Slow

jQuery.append() is painfully slow.

Initial Benchmark

I was playing around with WolfCage, the Wolfram Cellular Automata Generator that I built a year ago and I noticed that generating the board was ridiculously slow. I did a few benchmarks and found that the average time to generate a board is just over one second (~1086ms). The board has 11,325 cells (151 x 75). That is just over 10 cells per millisecond. D'oh!

Identifying the Bottleneck

I started looking through the code, trying to figure out the bottleneck. Each row is generated via a loop that calls a function to build the HTML for a cell based on its row and column position. The last call in that function is a jQuery.append() -- putting the individual cell's HTML onto the board. This was being performed on every iteration.

Solution

I changed the function to return a string of HTML creating the whole row, and then $.append() after the row is built.

After this change, the average run time to generate a board is 170ms. This is a ~6x increase!

Reminds me of a quote by Steve McConnell:

"The problem with quick and dirty...is that dirty remains long after quick has been forgotten."

UPDATE: I decided to get rid of jQuery completely and I rebuilt WolfCage using vanilla js.

Written by
Published
Email destin{AT}destinmoulton.com if you have any comments or questions.