Mapping bitmask values using arithmetic vs bitwise operators

Benchmark created on


Description

Compare performance of modulo/remainder mapping vs bitwise operators to do mapping for bitmask values

Setup

const exampleValues = [1032, 1, 320, 4381, 131071, 131072, 0]

Test runner

Ready to run.

Testing in
TestOps/sec
Modulo mapping
const getICDInstructions = (
	hintBitmap,
	hintInstruction = ''
) => {
  console.log('getICDInstructions for value:', hintBitmap)
	const instructions = [];

	let remainder = 0;
	let bitIndex = 0;
	let hintBitmapCopy = hintBitmap;

	do {
		remainder = hintBitmapCopy % 2;
		if (remainder === 1) {
			console.log(`bitIndex: ${bitIndex}`);
		}
		bitIndex += 1;
		hintBitmapCopy = Math.trunc(hintBitmapCopy / 2);
	} while (hintBitmapCopy > 0);

	return instructions;
};

exampleValues.forEach((val) => {
  getICDInstructions(val);
});

ready
Bitwise operators
const getICDInstructions = (
	hintBitmap,
	hintInstruction = ''
) => {
  console.log('getICDInstructions for value:', hintBitmap)
	const instructions = [];

	// Early return if no bits are set
	if (hintBitmap === 0) {
		return instructions;
	}

	// Check only valid bit positions (0-16 for 32-bit integer).
	for (let bitIndex = 0; bitIndex <= 16; bitIndex++) {
		// Check if bit at position bitIndex is set
		if ((hintBitmap & (1 << bitIndex)) !== 0) {
			console.log(`bitIndex: ${bitIndex}`);
		}
	}

	return instructions;
};

exampleValues.forEach((val) => {
  getICDInstructions(val);
});
ready

Revisions

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