WebGL2 Scalar Value Checks

Benchmark created on


Description

Tests if it is more efficient to compare the existing value of a scalar with an incoming value and update it if they differ or to just update it.

Preparation HTML

<canvas id="test"></canvas>

Setup

const canvas = document.querySelector("canvas#test");
const gl = canvas.getContext("webgl2");

const vss = `\
#version 300 es

uniform float u_scalar;

void main() {
	gl_Position = vec4(u_scalar);
}
`;

const fss = `\
#version 300 es

precision mediump float;

out vec4 outColor;

void main() {
	outColor = vec4(0, 0, 0, 1);
}
`;

function makeShader(src, type) {
	const out = gl.createShader(type);
	gl.shaderSource(out, src);
	gl.compileShader(out);
	
	if (!gl.getShaderParameter(out, gl.COMPILE_STATUS)) {
		throw new Error(gl.getShaderInfoLog(out));
	}
	
	return out;
}

const vs = makeShader(vss, gl.VERTEX_SHADER);
const fs = makeShader(fss, gl.FRAGMENT_SHADER);

const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
	throw new Error(gl.getProgramInfoLog(program));
}

const scalarLoc = gl.getUniformLocation(program, "u_scalar");

const scalar = 0;

gl.useProgram(program);

gl.uniform1f(scalarLoc, scalar);
let scalarValueCache = scalar;

Teardown

gl.deleteProgram(program);

Test runner

Ready to run.

Testing in
TestOps/sec
Re-Set without Check
gl.uniform1f(scalarLoc, scalar);

ready
Set if Not Equivalent with Cached Value
if (scalar === scalarValueCache) {
	// return;
} else {
	gl.uniform1f(scalarLoc, scalar);
	scalarValueCache = scalar;
}

ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.