kosiakMD
kosiakMD

Reputation: 1062

Does complexity depend on the size of numbers in JS engine?

Does it matter how big numbers to calculate in JavaScript Engine, especially V8 in NodeJS?

The applicable example: I'm calculating in loops time date variables in milliseconds and have some time variables in minutes. I have doubts should I convert all times from minutes to milliseconds to have everything consistent, or vice-versa to have smaller values for easer calculation?

Converting complexity from milliseconds to minutes (I believe insignificant) - 2 variables per loop. From minutes to milliseconds - 2 variables once.

Upvotes: 0

Views: 254

Answers (1)

Bergi
Bergi

Reputation: 665276

Apart from BigInt, all JS math is done on 64-bit floating point numbers1. All operations have constant time complexity, they do not depend on the values they are working with.

Either way, start by writing clear, idiomatic and correct code. It will be optimised well enough by the engine. Only when you identify a performance bottleneck in a particular part of the code, and think you can outsmart the engine optimisations, benchmark your different approaches.

1: Some engines, V8 in particular, optimise storage and computation for small integers (like most array indices). Operations on them might be faster than a floating-point operation, but still they have constant time complexity and do not depend on which integers they work with.

Upvotes: 2

Related Questions