Three.js Instancing Performance (100k Objects)
Render up to 100,000 cubes in Three.js and compare individual meshes, InstancedMesh with CPU-updated matrices, and InstancedMesh animated entirely on the GPU from gl_InstanceID, with draw calls and render-time stats.
Key topics: three.js instancedmesh, instancing, draw calls, performance, gpu animation, gl_instanceid
Game Over
What this code does
- Draw Calls: separate meshes cost one draw call each, so thousands of objects become CPU-bound before the GPU is busy.
- InstancedMesh: one geometry, one material and N matrices render all copies in a single draw call.
- CPU Matrices: animating via `setMatrixAt` rewrites and re-uploads the whole instance buffer every frame.
- GPU Animation: `onBeforeCompile` adds per-instance motion from gl_InstanceID in the vertex shader, with no CPU work per object.
- Per-Instance Colour: `setColorAt` gives every cube its own colour without extra materials.
- Controls: technique, object count (individual meshes capped at 10k) and animation.
Related Demos
Continue Learning
JavaScript Implementation
// One draw call for 50,000 cubes, animated on the GPU from gl_InstanceID
const material = new THREE.MeshStandardMaterial()
material.onBeforeCompile = (shader) => {
shader.uniforms.uTime = uniforms.uTime
shader.vertexShader = shader.vertexShader
.replace('#include <common>', '#include <common>\nuniform float uTime;')
.replace('#include <begin_vertex>', `#include <begin_vertex>
transformed.y += sin(uTime * 2.0 + float(gl_InstanceID) * 0.37) * 0.6;`)
}
const cubes = new THREE.InstancedMesh(new THREE.BoxGeometry(0.4, 0.4, 0.4), material, 50000)
const m = new THREE.Matrix4()
for (let i = 0; i < 50000; i++) cubes.setMatrixAt(i, m.makeTranslation(Math.random() * 100 - 50, 0, Math.random() * 100 - 50))
scene.add(cubes) // no per-frame CPU work: the vertex shader animates every instance