<!--your preparation HTML code goes here-->
function bigIntToUint8Array64LE_direct(num) {
const result = new Uint8Array(8);
result[0] = Number(num & 0xffn);
result[1] = Number((num >> 8n) & 0xffn);
result[2] = Number((num >> 16n) & 0xffn);
result[3] = Number((num >> 24n) & 0xffn);
result[4] = Number((num >> 32n) & 0xffn);
result[5] = Number((num >> 40n) & 0xffn);
result[6] = Number((num >> 48n) & 0xffn);
result[7] = Number((num >> 56n) & 0xffn);
return result;
}
function bigIntToUint8Array64LE_hex(value) {
const hex = value.toString(16).padStart(8 * 2, '0');
const bytes = new Uint8Array(8);
for (let i = 0; i < 8; i++) {
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return bytes;
}
bigIntToUint8Array64LE_direct(538753629635n)
bigIntToUint8Array64LE_hex(538753629635n)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Direct | |
Hex |
Test name | Executions per second |
---|---|
Direct | 5327440.5 Ops/sec |
Hex | 1392690.5 Ops/sec |
The benchmark provided assesses two different approaches to converting a BigInt (specifically, a 64-bit value) into a Uint8Array (an object representing an array of 8-bit unsigned integers) in JavaScript. The benchmark uses the following two methods:
Direct Method (bigIntToUint8Array64LE_direct
):
0xffn
to retrieve the least significant byte and then right-shifting the Bits to get the subsequent bytes.Hex Method (bigIntToUint8Array64LE_hex
):
The benchmark results show the performance of each method in terms of executions per second:
Clearly, the direct method is far more performant than the hex method. This difference highlights the efficiency of direct bitwise manipulation compared to string conversion and parsing.
While the two methods outlined are effective, there are other potential alternatives for converting BigInts to byte arrays, such as employing existing libraries (like Buffer
from Node.js or third-party libraries such as big-integer
or bignumber.js
). However, these libraries often come with their own overhead and dependency management, whereas the methods provided are native and do not rely on external resources.
In conclusion, when comparing these two approaches, it is essential to balance performance and readability based on the specific use case and audience. For high-performance needs and environments, the direct method is a clear choice, while for code clarity, especially in collaborative environments, the hex method may be preferred.