Why ironing stuttered on big boards: a performance pass on a bead game
Here's how ironing works in Slow Beads: you hold the iron down and move it in slow circles over the board, and the beads underneath gradually melt until the whole piece is fused flat. On small patterns it always felt smooth. On a 104×104 board, it started to drag.
Where the time went
A 104×104 board has 10,816 cells. Ironing progress came from a function called meltAvg(), which added up every cell's melt level and divided by the total. The trouble was that it walked the entire board on every call, and it got called three times per frame.
// Before: every call walks the entire board
function meltAvg(){
let s = 0;
G.p.cells.forEach((c, i) => { if (c !== '.') s += G.melt[i] });
return s / G.p.total;
}
The other two bottlenecks were better hidden. First, the status bar wrote textContent every frame, triggering layout even when the text was identical. Second, the auto-melt at the end: on a large board, more than a thousand cells can cross the next melt threshold in the same frame, and repainting them all at once cost that frame tens of milliseconds.
Three fixes
- A running sum. Whenever a cell's melt value changes, add the difference to a total. The average no longer needs a full pass.
- Only write text when it changes. If the status bar would say the same thing as last frame, leave the DOM alone.
- Throttle redraws. Cells waiting to be repainted go into a set; each frame paints at most 256 and leaves the rest for the next one.
function meltAvg(){ return G.msum / G.p.total }
const MQ = m => Math.round(m * 8) / 8, MDIRTY_MAX = 256;
let nd = 0;
for (const i of G.mdirty) {
if (nd++ >= MDIRTY_MAX) break;
paintCell(L, i); addCell(i, .6); G.mdirty.delete(i);
}
Making sure it actually got smoother
"Feels smoother" is subjective, so while I was at it I added a performance script that runs the same ironing session under three profiles: desktop at full speed, an emulated Pixel 7 with the CPU throttled to a quarter, and a tablet throttled the same way. It records frame intervals, long tasks and per-function timings, which gives me a baseline the next time I touch the ironing code.
This shipped in v1.8.11. The very next release, v1.8.12, fixed a different hitch on large boards, the moment ironing finishes. That one gets its own post.