Converting Float to Integer: Math.floor() vs ... (v2)

Revision 2 of this benchmark created on


Description

Various popular methods to cast Float to Int. Added context code that observes and acts upon test calculations. This is to prevent "dead code elimination" and encourage realistic optimization from the JavaScript VM.

Preparation HTML

<p id="acc"></p>

Setup

function update(a, b) {
	return (b - a) / 2.0;
}

function finish(acc) {
	let elem = document.getElementById("acc");
	elem.innerText = acc;
}

function numbers() {
    const size = 16384;
	const array = new Int32Array(size);
	crypto.getRandomValues(array);
    const floats = new Float32Array(size);
    for(let x = 0; x < size; x++)
        floats[x] = array[x] / size;
	return floats;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Math.floor
let acc = 0.0;
for (const num of numbers()) {
  let res = Math.floor(num);
  acc += update(res, acc);
}
finish(acc);
ready
Math.trunc
let acc = 0.0;
for (const num of numbers()) {
  let res = Math.trunc(num);
  acc += update(res, acc);
}
finish(acc);
ready
Bitwise OR
let acc = 0.0;
for (const num of numbers()) {
  let res = num | 0;
  acc += update(res, acc);
}
finish(acc);
ready
Bitwise RIGHT
let acc = 0.0;
for (const num of numbers()) {
  let res = num >> 0;
  acc += update(res, acc);
}
finish(acc);
ready
Bitwise LEFT
let acc = 0.0;
for (const num of numbers()) {
  let res = num << 0;
  acc += update(res, acc);
}
finish(acc);
ready
Bitwise NOT
let acc = 0.0;
for (const num of numbers()) {
  let res = ~~num;
  acc += update(res, acc);
}
finish(acc);
ready
parseInt
let acc = 0.0;
for (const num of numbers()) {
  let res = parseInt(num);
  acc += update(res, acc);
}
finish(acc);
ready

Revisions

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