Skip to content

(value + 0.5) << 0 might actually be slightly faster, and is more accurate #27

@jeffpeck10x

Description

@jeffpeck10x

For the round function, I noticed that you use 0.49, which seems to give a speed boost in some circumstances, but with random numbers, apparently not.

function createRandom(count, scale) {
  const a = new Float64Array(count);
  for (let i = 0; i < count; i++) {
    a[i] = Math.random() * scale;
  }
  return a;
}

function roundA(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.49) << 0;
  }
}

function roundB(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = (a[i] + 0.5) << 0;
  }
}

function trunc(a, b) {
  for (let i = 0; i < a.length; i++) {
    b[i] = a[i] << 0;
  }
}

function main() {
  const a = createRandom(100000000, 1000);
  const b = new Int32Array(a.length);
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
  console.time("roundA");
  roundA(a, b);
  console.timeEnd("roundA");
  console.time("roundB");
  roundB(a, b);
  console.timeEnd("roundB");
  console.time("trunc");
  trunc(a, b);
  console.timeEnd("trunc");
}

main();
roundA: 301.97607421875 ms
roundB: 184.259033203125 ms
trunc: 179.185791015625 ms
roundA: 177.18603515625 ms
roundB: 179.783935546875 ms
trunc: 178.2119140625 ms

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions