jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
-20.5 rounds to -20, but what if it rounded to -21?
<script>
const CASES = [];
// 10 million random numbers
const N = 10000000;
// on values ±1,000,000
const R = 1000000;
const R2 = 2 * R;
for (let i = 0; i < N; i++) {
CASES.push(Math.random() * 2 * R - R);
}
</script>
function test (f) {
for (const n of CASES) f(n);
}
// round the magnitude then multiply by the sign
function round1 (n) {
return Math.round(Math.abs(n)) * Math.sign(n);
}
// conditionally use floor for negative numbers
// with a fractional part of 0.5
function round2 (n) {
return n >= 0 ? Math.round(n) :
n % 0.5 === 0 ? Math.floor(n) :
Math.round(n);
}
// same as 2 w/ slightly different conditional
function round3 (n) {
return (n >= 0 || n % 0.5 !== 0) ?
Math.round(n) :
Math.floor(n);
}
Ready to run.
Test | Ops/sec | |
---|---|---|
round magnitude * sign |
| ready |
conditional floor |
| ready |
same as 2 w/ consolidated condition |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.