Reputation: 3547
In JavaScript there are two typed array constructors that can store rather large numbers:
const longs = new BigInt64Array()
const doubles = new Float64Array()
They both represent arrays of 64-bit signed integers and floating point numbers, respectively.
Is there any reason to use BigInt64Array
if I'm not storing numbers larger than Number.MAX_SAFE_INTEGER
?
The only upside I can think of to use BigInt64Array
(even if your numbers are less than Number.MAX_SAFE_INTEGER
) is if you want to enforce an integer type while storing your numbers, since the constructor will throw an error if one of the elements is a floating point number:
const arr = new BigInt64Array([900719925.4534]);
// Uncaught TypeError: Cannot convert 900719925.4534 to a BigInt
However, the downsides are that for each known integer you want to add, you have to remember to append n
to it like so:
const arr = new BigInt64Array([523235n, 1093n, 3238n]);
In addition, if only the runtime knows the integers, you have to use the BigInt(value)
function to convert them to the proper type:
const arr = new BigInt64Array([BigInt(a), BigInt(b), BigInt(c)]);
The upside to Float64Array
is that it works right out of the gate with primitive JavaScript numbers (no number literal suffix or converter function is required).
Is my reasoning correct on the usefulness of BigInt64Array
?
Upvotes: 0
Views: 39
Reputation: 40501
As you observe, converting Numbers to BigInts just to store them in an array (and back to Numbers when reading them from the array) is annoying. It's also inefficient, because it creates extra work for the CPU (mostly for the allocation, and also a little for the actual conversion between different numerical formats). As a very general rule of thumb in many programming situations, it's nice to avoid conversions.
So I'd say: Use a BigInt64Array
if you're working with BigInt
s anyway, prefer a Float64Array
if the rest of your code uses Number
s.
There are some conceivable reasons why you might be working with BigInts. Perhaps you want your code to be able to handle integer operations beyond MAX_SAFE_INTEGER
, or bitwise operations beyond 32-bit values. Or, even if you're sure that your own code won't ever see such large values, perhaps you're using a third-party library that's ready for them. Or, as a variant of the "library" scenario, perhaps you're working with a WebAssembly module that uses i64
values in its public interface (because it was compiled from C++ int64_t
types or similar).
So, BigInt64Array
does have more uses than just "I want more errors to be thrown", but in many cases using Numbers and storing them in a Float64Array
, or even plain untyped Array
is just fine. Do keep that latter point in mind: why do you think you need a typed array to begin with? Perhaps unintuitively, regular arrays tend to be more efficient in many cases.
Upvotes: 1