Comparing Some Bitwise Operations and Similar Tests

Benchmark created on


Description

https://stackoverflow.com/questions/78362457/is-there-a-general-approach-for-optimizing-bitwise-expressions-that-distinguish < trying some of the solutions here, along with some more naive solutions.

Setup

const N = 60000;
const cases = new Array(N).fill(0).map(() =>
  Math.floor(Math.random() * 8)
);

function run (test) {
	let guys = 0;
	for (const x of cases) if (test(x)) guys++;
	console.log(`got ${guys} / ${N} guys`);
}

Test runner

Ready to run.

Testing in
TestOps/sec
chained boolean `||` (reference implementation)
run(
  x => x === 1 || x === 3 || x === 4 || x === 6
);
ready
switch
run(x => {
	switch (x) {
		case 1:
		case 3:
		case 4:
		case 6:
		  return true;
		default:
		  return false;
	}
})
ready
smallbrain test 1
run(x => x < 4 ? (x & 1) : !(x & 1));
ready
1st answer
run(x =>
  1 << x & (1 << 1 | 1 << 3 | 1 << 4 | 1 << 6)
);
ready
2nd answer
run(x => ((x >>> 2) ^ x) & 1)
ready
3rd answer
run(x => (x & 1) !== (x >>> 2));
ready
LUT
var LUT = [0, 1, 0, 1, 1, 0, 1, 0]
run(x => LUT[x]);
ready
set
var BYEAHS = new Set([1,3,4,6])
run(x => BYEAHS.has(x));
ready
object, lol
const OBJ = {
	0: false,
	1: true,
	2: false,
	3: true,
	4: true,
	5: false,
	6: true,
	7: false,
}
run(x => OBJ[x])
ready
TRYHARD object
const THO = Object.create(null, {
	0: { value: false },
	1: { value: true },
	2: { value: false },
	3: { value: true },
	4: { value: true },
	5: { value: false },
	6: { value: true },
	7: { value: false },
})

run(x => THO[x]);
ready
map?
const MAP = new Map([
    [0, false],
    [1, true],
    [2, false],
    [3, true],
    [4, true],
    [5, false],
    [6, true],
    [7, false],
])

run(x => MAP.get(x));
ready

Revisions

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