WebGL2 4x1 Vector Value Checks

Benchmark created on


Description

Tests if it is more efficient to compare the existing value of a 4x1 vector 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 vec4 u_vector;

void main() {
	gl_Position = u_vector;
}
`;

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 vecLoc = gl.getUniformLocation(program, "u_vector");

const vector = new Float32Array([0, 1, 2, 3]);

gl.useProgram(program);

const [x2, y2, z2, w2] = [...vector];
gl.uniform4fv(vecLoc, vector);
let vectorValueCache = [x2, y2, z2, w2];

Teardown

gl.deleteProgram(program);

Test runner

Ready to run.

Testing in
TestOps/sec
Re-Set without Check
gl.uniform4fv(vecLoc, vector);
ready
Set if Not Equivalent with Cached Value
const [x, y, z, w] = [...vector];
if (
	(x === vectorValueCache[0] &&
		y === vectorValueCache[1] &&
		z === vectorValueCache[2] &&
		w === vectorValueCache[3]) ||
	typeof x === "undefined" ||
	typeof y === "undefined" ||
	typeof z === "undefined" ||
	typeof w === "undefined"
) {
	// return;
} else {
	gl.uniform4fv(vecLoc, vector);
	vectorValueCache = [x, y, z, w];
}
ready

Revisions

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