Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript typed arrays: 64-bit integers?

Tags:

JavaScript typed arrays, implemented in Firefox 4 and Chrome 7, are a very efficient way of storing and working with binary data in JavaScript. However, the current implementations only provide integer views up to 32 bits per member, with Int32Array and Uint32Array. Are 64-bit integer views being planned for implementation? How can I implement 64-bit integer views? How much slower will they be?

like image 923
Delan Azabani Avatar asked May 18 '11 07:05

Delan Azabani


1 Answers

ECMAScript 2020 now has a built-in BigInt type, with BigInt64Array and BigUint64Array typed arrays. The internal 64-bit representations are converted to and from BigInt values, which are needed to keep the full precision.

BigInt and the array types are still relatively new, so see below if you need to support older browsers or Node versions. You can use resources like CanIUse.com to see what browsers to help you decide if it's an option or not. Polyfills could also be an option as a workaround until you phase out support for unsupported browsers.


Answer for older browsers/Node environments:

There's no practical way to implement an Int64Array, because all numbers in JavaScript are 64-bit floating point numbers, which only have 53 bits of precision. Like Simeon said in his comment, you could use a big integer library, but it would be much slower.

If you really need an array of 64-bit integers, regardless of performance, the Google Closure library has a 64-bit Long class that I would imagine is faster than a more general big integer library. I've never used it though, and I don't know if you can separate it easily from the rest of the library.

like image 158
Matthew Crumley Avatar answered Sep 21 '22 15:09

Matthew Crumley