var saltVal = crypto.getRandomValues(new Uint8Array(16));
function arrayBufferToHexString(bytes) {
bytes = new Uint8Array(bytes);
var hex = new Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
hex[i] = ("0" + bytes[i].toString(16)).slice(-2);
}
return hex.join("");
}
function bytesToHexString(bytes) {
bytes = new Uint8Array(bytes);
var hexBytes = [];
for (var i = 0; i < bytes.length; i++) {
var byteString = bytes[i].toString(16);
if (byteString.length < 2) byteString = "0" + byteString;
hexBytes.push(byteString);
}
return hexBytes.join("");
}
function buf2hex(buffer) { // buffer is an ArrayBuffer
return [new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
function hex(arrayBuffer)
{
const asciiCodes = new Uint8Array(
Array.prototype.map.call(
"0123456789abcdef",
char => char.charCodeAt()
)
);
const buff = new Uint8Array(arrayBuffer);
const charCodes = new Uint8Array(buff.length * 2);
for (let i = 0; i < buff.length; ++i)
{
charCodes[i * 2] = asciiCodes[buff[i] >>> 4];
charCodes[i * 2 + 1] = asciiCodes[buff[i] & 0xf];
}
return String.fromCharCode(charCodes);
}
function hex2(arrayBuffer)
{
return Array.prototype.map.call(
new Uint8Array(arrayBuffer),
n => n.toString(16).padStart(2, "0")
).join("");
}
arrayBufferToHexString(saltVal);
bytesToHexString(saltVal)
buf2hex(saltVal)
hex(saltVal)
hex2(saltVal)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
directly set | |
push values | |
buf2hex() | |
precomputed ASCII with shift | |
array prototype map |
Test name | Executions per second |
---|---|
directly set | 2491597.0 Ops/sec |
push values | 3310311.5 Ops/sec |
buf2hex() | 1640268.4 Ops/sec |
precomputed ASCII with shift | 861354.1 Ops/sec |
array prototype map | 1204383.1 Ops/sec |
The provided benchmark focuses on measuring the performance of five different methods for converting an ArrayBuffer (a binary data representation) to a hexadecimal string. Let's break down the benchmark, its methods, their pros and cons, and considerations for software engineers.
arrayBufferToHexString(saltVal);
(directly set):
bytesToHexString(saltVal)
(push values):
push()
to accumulate hexadecimal strings into an array and joins them after the loop.buf2hex(saltVal)
:
hex(saltVal)
(precomputed ASCII with shift):
hex2(saltVal)
(array prototype map):
Array.prototype.map()
on a newly created Uint8Array to convert byte values to a hex string format.In the benchmark results, "push values" using bytesToHexString
emerged as the fastest method, with 3,310,311.5 executions per second. The subsequent performances were as follows:
In summary, this benchmark illustrates various approaches to converting binary data to a readable format, weighing performance against complexity and maintainability. Understanding the nuances of these methods can help software engineers optimize their code for different applications effectively.