How to Destroy a gpu.js Kernel to Free Memory

Managing GPU memory is critical when running high-performance computations in JavaScript, as lingering WebGL contexts can quickly cause memory leaks and degrade browser performance. This article explains how to properly dispose of and destroy a gpu.js kernel instance, along with its associated textures and contexts, ensuring system and graphics resources are safely reclaimed.

Using the destroy() Method on a Kernel

When you create a kernel in gpu.js, it compiles a WebGL program and reserves GPU memory for execution. To release these resources when a kernel is no longer needed, call the .destroy() method directly on the kernel instance.

const { GPU } = require('gpu.js');
const gpu = new GPU();

// 1. Create the kernel
const multiplyMatrix = gpu.createKernel(function(a, b) {
  let sum = 0;
  for (let i = 0; i < 512; i++) {
    sum += a[this.thread.y][i] * b[i][this.thread.x];
  }
  return sum;
}).setOutput([512, 512]);

// 2. Execute the kernel
const result = multiplyMatrix(matrixA, matrixB);

// 3. Destroy the kernel instance to free GPU memory
multiplyMatrix.destroy();

Calling destroy() cleans up the underlying WebGL shaders, framebuffers, and programs associated with that specific computation.

Releasing Output Textures

If your kernel runs in pipeline mode (setPipeline(true)), the kernel outputs an internal texture rather than a JavaScript array. These textures consume GPU VRAM independently of the kernel.

To free memory allocated by pipelined output textures, call .delete() on the texture object:

const renderKernel = gpu.createKernel(function() {
  return this.thread.x;
})
.setOutput([1024])
.setPipeline(true);

const textureResult = renderKernel();

// Dispose of the texture once it is no longer required
textureResult.delete();

// Clean up the kernel itself
renderKernel.destroy();

Destroying the Entire GPU Context

If your application has finished all GPU processing and no further kernels will be created, you should dispose of the parent GPU instance. This releases the entire WebGL context and all associated internal caches back to the operating system.

// Clean up all kernels and release the WebGL context entirely
gpu.destroy();

Best Practices for Lifecycle Management