Memory Allocation Discipline Example
1 min readRapid overview
Memory Allocation Example (JavaScript)
This example highlights how frequent allocations can impact performance and how to avoid them.
Scenario
You render a list of items every animation frame and create new arrays each time.
const renderFrame = (items: number[]) => {
const doubled = items.map((item) => item * 2);
draw(doubled);
};
Improvement
Reuse arrays when possible or move allocation outside hot loops.
const buffer: number[] = [];
const renderFrame = (items: number[]) => {
buffer.length = 0;
for (const item of items) buffer.push(item * 2);
draw(buffer);
};
Takeaway
Minimize allocations in tight loops to reduce GC pressure and dropped frames.