Avoid unnecessary allocations
Why Avoid Memory Allocations?
JavaScript runs in a garbage-collected environment. That means every time you create a new object such as new Vector3()
, the runtime allocates memory for it, which itself takes time. Eventually, when it's no longer used, the garbage collector will analyse references and reclaim that memory. This process sounds automatic and helpful (and it is), but frequent allocations and deallocations can cause performance hiccups, especially in real-time graphics applications like games.
In your game, your rendering loop will run 60+ times per second. If you're constantly creating new vectors, matrices, or objects each frame, the garbage collector can kick in often, leading to dropped frames or stuttering animations. To ensure smooth performance, it’s crucial to reuse objects and minimize allocations, especially inside the render update loop.
Best Practices for Avoiding Garbage Collection
1. Reuse Vector3, Vector2, Matrix4, and other Math Objects
Bad:
function update() {
const direction = new Vector3().subVectors(target.position, camera.position);
// ...
}
Good:
const direction = new Vector3(); // allocate once
function update() {
direction.subVectors(target.position, camera.position);
// ...
}
✅ Allocate once outside the loop and reuse.
2. Avoid Anonymous Math Expressions in Loops
Each chained call like .clone().add()
creates new objects under the hood unless you’re careful.
Bad:
function update() {
const newPos = object.position.clone().add(new Vector3(0, 1, 0));
// ...
}
Good:
const newPos = new Vector3()
const up = new Vector3(0, 1, 0);
function update() {
newPos.copy(object.position).add(up);
// ...
}
✅ Prefer
copy()
andset()
overclone()
inside tight loops.
3. Use Temporary Scratch Variables
Keep shared "temp" variables for calculations to avoid repeatedly creating them.
const tempVec3 = new Vector3();
const tempQuat = new Quaternion();
const tempScale = new Vector3();
function updateTransform(object) {
object.matrixWorld.decompose(tempVec3, tempQuat, tempScale);
// Reuse tempVec3, tempQuat, tempScale
}
Use Chrome DevTools to Monitor Allocations
Use the "Performance" and "Memory" tabs in Chrome DevTools:
Record a session.
Look for spikes in JS heap or GC pauses.
Hover over memory allocations to see what’s triggering them.
Last updated