noctcore-three/no-allocation-in-frame-loop
noctcore-three/no-allocation-in-frame-loop
- Package
- three v0.1.0
- Preset
- recommended
- Severity
- error
- Autofix
- No
- Suggestions
- No
- Options
- Optional
- Type info
- Not needed
No three.js math objects or GPU resources constructed, or transforms cloned, inside a frame loop.
A frame loop runs 60 to 120 times a second. A new Vector3() in it is thousands of short-lived
objects a minute, and the garbage collector pays for them in pauses that show up as dropped frames.
A geometry, material or texture built there is worse: each one is uploaded to the GPU and never
disposed. Create the object once and reuse it with .set() and .copy():
import * as THREE from 'three';import { useFrame } from '@react-three/fiber';
export function Float({ mesh }: { mesh: { current: THREE.Mesh } }) { useFrame(() => { mesh.current.position.lerp(new THREE.Vector3(0, 1, 0), 0.1); }); return null;}import * as THREE from 'three';import { useFrame } from '@react-three/fiber';
const target = new THREE.Vector3(0, 1, 0);
export function Float({ mesh }: { mesh: { current: THREE.Mesh } }) { useFrame(() => { mesh.current.position.lerp(target, 0.1); }); return null;}What it flags
Section titled “What it flags”new X() inside a frame loop, where X is imported from three (named, or through
import * as THREE) and is either:
- a math class:
Vector2,Vector3,Vector4,Matrix3,Matrix4,Quaternion,Euler,Color,Box2,Box3,Sphere,Ray,Plane,Line3,Triangle,Spherical,Cylindrical,Frustum,Raycaster; - a GPU resource: any
*Geometry,*Material,*Textureor*RenderTargetclass.
It also flags .clone() with no arguments on a transform field of a three.js object, which
allocates the same way: mesh.current.position.clone(), camera.quaternion.clone(),
dummy.matrixWorld.clone(). The field is one of position, quaternion, rotation, scale,
up, matrix, matrixWorld, matrixWorldInverse, projectionMatrix and
projectionMatrixInverse, and two things must hold:
- the object is known to be a three.js one from the file’s own declarations: a variable built
with
newfrom a class imported from three.js (alsouseMemo(() => new THREE.Object3D(), [])), a variable or parameter typed as a three.js type (mesh: THREE.Mesh),ref.currentofuseRef<THREE.Mesh>(),useRef(new THREE.Group())or aRefObject<THREE.Mesh>, and thecameraandsceneReact Three Fiber hands out (useFrame(({ camera }) => ...),state.camera,useThree((state) => state.camera),const { scene } = useThree()); - the call runs on every frame the object exists (see the conditions below).
import * as THREE from 'three';import { useFrame } from '@react-three/fiber';import { useRef } from 'react';
export function Follow({ offset }: { offset: THREE.Vector3 }) { const mesh = useRef<THREE.Mesh>(null!); useFrame(({ camera }) => { camera.position.lerp(mesh.current.position.clone().add(offset), 0.1); }); return <mesh ref={mesh} />;}import * as THREE from 'three';import { useFrame } from '@react-three/fiber';import { useRef } from 'react';
const target = new THREE.Vector3();
export function Follow({ offset }: { offset: THREE.Vector3 }) { const mesh = useRef<THREE.Mesh>(null!); useFrame(({ camera }) => { camera.position.lerp(target.copy(mesh.current.position).add(offset), 0.1); }); return <mesh ref={mesh} />;}A frame loop is the callback of R3F’s useFrame (imported from @react-three/fiber), the callback
of renderer.setAnimationLoop(), or a function that schedules itself with
requestAnimationFrame(name) (also requestAnimationFrame(this.name) in a class). Callbacks are
matched inline or by reference (setAnimationLoop(tick) resolves tick through scope), and inline callbacks inside the loop (items.forEach(...)) count too.
import { Vector3 } from 'three';
function animate() { requestAnimationFrame(animate); mesh.position.add(new Vector3(0, 0.01, 0)); renderer.render(scene, camera);}animate();import { Vector3 } from 'three';
const step = new Vector3(0, 0.01, 0);
function animate() { requestAnimationFrame(animate); mesh.position.add(step); renderer.render(scene, camera);}animate();What it does not flag
Section titled “What it does not flag”- Files that import neither
three(or athree/*subpath),three-stdlib, an@react-three/*package nor one ofextraModules: the rule only runs in three.js code, so another engine’s API with the same names (a Phaser or Babylon camera) is never read as three.js. Only staticimportdeclarations count: a file that loads three.js only throughimport()orrequire()is skipped, which can hide a report but never adds one. - Lazy initialisation that runs once:
ref.current ??= new Vector3(),cache.v = cache.v ?? new Vector3()(the result goes back to the target the left side reads), andref.current = new Vector3()in a branch that runs only while that same target is unset (if (!ref.current),if (ref.current == null),if (typeof ref.current === 'undefined')), or after an early return that fires whenever it is set (if (ref.current) return;, also when thatifsits in a bare block above the assignment). A fallback that is not stored back (const v = p.v || new Vector3()) and a guard on another name or with the opposite polarity (if (!ref.current) return;) are still reported. So is a target the same pass empties again after filling it (ref.current = undefined,delete cache.v, orcache = {}forcache.v, as a plain statement after the assignment), because the next frame then initialises it again. An emptying that runs on another pass is not counted: under a branch (if (!dragging) { start.current = null; return; }), before the assignment, behind areturn, or in a nested function. - A local class or variable that shadows the three.js import where it is used
(
class Vector3 {}inside the loop). - Classes that are not imported from
three(a localVector3class), and three.js classes that are neither math nor GPU resources (Group,Object3D). - A one-shot
requestAnimationFrame(() => ...), and a helper function declared inside the loop. .clone()on anything the file does not show to be a three.js object. Without type information the rule cannot tell aVector3from anything else with aclone()method, so the field name alone proves nothing:keys.up.clone(),player.position.clone()on an untyped prop or store value,ref.current.position.clone()onuseRef(null), a field of a call result or an indexed element (pick().position.clone(),meshes[i].position.clone()), athis.meshfield and a destructured prop typed on the pattern are all left alone. Other fields (velocity.clone(),controls.target.clone()) and a bareposition.clone()are too..clone()that runs only on some frames: under anif, a? :, the right side of&&/||/??or aswitchcase, or after an early return on such a condition (if (pressed) start = camera.position.clone()andif (!pressed.current) return; start = camera.position.clone()are the same code). A snapshot taken when something happens is not a per-frame cost; a clone that runs on every frame while a flag is set is missed for the same reason. A check that only asks whether the cloned object is there is not a condition:if (!mesh.current) return;,if (mesh.current) { ... }andmesh.current && ...aroundmesh.current.position.clone()are still reported. A check on another object, or one mixed with something else (if (!mesh.current || paused) return;), is a condition.- A clone stored once (
home.current ??= mesh.current.position.clone()), which is lazy initialisation like any other.
import * as THREE from 'three';import { useFrame } from '@react-three/fiber';
export function Float({ mesh, target }: { mesh: { current: THREE.Mesh }; target: { current?: THREE.Vector3 } }) { useFrame(() => { target.current ??= new THREE.Vector3(0, 1, 0); mesh.current.position.lerp(target.current, 0.1); }); return null;}Options
Section titled “Options”| Option | Type | Default | Meaning |
|---|---|---|---|
allowIn |
string[] (globs) |
[] |
Files the rule skips, matched against the absolute path and the path relative to the working directory or workspace root. |
extraModules |
string[] |
[] |
More module specifiers that mark a file as three.js code (a project module that re-exports three.js, such as @acme/engine); subpaths match too, and their imports count as three.js classes and R3F hooks. |
'noctcore-three/no-allocation-in-frame-loop': ['error', { allowIn: ['**/demos/**'] }]When not to use it
Section titled “When not to use it”Code whose loop runs rarely (a frameloop="demand" canvas that renders on interaction only) gains
little from hoisting, though it costs nothing either.
Related
Section titled “Related”no-react-state-in-frame-loop: the other per-frame cost, a React render on every frame.no-resource-creation-in-render: the same resources built in a component body.