Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: toFixed() vs. Math.floor(x * 10000)

Tags:

javascript

I need to compare two float values to a certain precision (that is 4 decimal places):

var float1 = 0.0025132741228718345;
var float2 = 0.0025132812393818293;

The two options I see:

Math.floor(float1 * 10000) === Math.floor(float2 * 10000); // 25 === 25

...or:

float1.toFixed(4) === float2.toFixed(4) // "0.0025" === "0.0025"

Since operation will happen 60 times a second and I was asking myself:

  1. which of the options has the higher performance?
  2. is one of the options more widely accepted?
  3. is there a third option?
like image 408
kraftwer1 Avatar asked Dec 19 '22 18:12

kraftwer1


1 Answers

function floor(f1, f2) {
    return Math.floor(f1 * 10000) === Math.floor(f2 * 10000);
}
function toFixed(f1, f2) {
    return f1.toFixed(4) === f2.toFixed(4);
}
function subtract(f1, f2) {
    return Math.abs(f1 - f2) < 0.00001;
}
function test(fn) {
     console.time(fn.name);
     for (let i = 0; i < 1000000; ++i) {
         fn(Math.random(), Math.random());
     }
     console.timeEnd(fn.name);
}
for (const fn of [floor, toFixed, subtract]) {
    test(fn);
}

Engine benchmarks

v8 (Chromium-based browsers)

  • floor: 204.911 ms
  • toFixed: 4145.529 ms
  • subtract: 292.390 ms

SpiderMonkey (Firefox-based browsers)

  • floor: 566.81ms
  • toFixed: 683.56ms
  • subtract: 423.76ms

Between the two options that you gave, The Math.floor approach is the faster one.

Might be a wise choice to go for subtract, though.

(Run this benchmark yourself if you don't believe me.)

like image 164
Chiru Avatar answered Jan 09 '23 13:01

Chiru