var hexVal = 'ed0c356af33bb022afe7c5f8557ad89c';
function hexToArrayBuffer(hex) {
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map((h) => {
return parseInt(h, 16);
})).buffer;
}
function hexStringToUint8Array(hexString) {
var arrayBuffer = new Uint8Array(hexString.length / 2);
for (var i = 0; i < hexString.length; i += 2) {
var byteValue = parseInt(hexString.substr(i, 2), 16);
arrayBuffer[i / 2] = byteValue;
}
return arrayBuffer;
}
hexToArrayBuffer(hexVal)
hexStringToUint8Array(hexVal)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex match | |
parseInt 16 |
Test name | Executions per second |
---|---|
regex match | 232294.2 Ops/sec |
parseInt 16 | 757726.8 Ops/sec |
Let's break down the provided benchmark and its components.
Benchmark Definition JSON
The benchmark definition JSON contains information about the test case, including:
Name
: The name of the test case.Description
: A brief description of what the test case is trying to measure.Script Preparation Code
: A JavaScript code snippet that sets up the test case. This includes the hexToArrayBuffer
and hexStringToUint8Array
functions, which are used to convert hexadecimal strings to Uint8Arrays.Html Preparation Code
: An empty string, indicating that no HTML preparation code is required for this benchmark.Individual Test Cases
The benchmark definition JSON also contains two individual test cases:
hexToArrayBuffer
function.parseInt
function with base 16 (i.e., parseInt(16)
).Options Compared
The two test cases compare different approaches for converting hexadecimal strings to arrays or Uint8Arrays:
hexToArrayBuffer
: This approach uses a custom function to convert the hexadecimal string to an array buffer.parseInt 16
: This approach uses the built-in parseInt
function with base 16 (i.e., parseInt(16)
).Pros and Cons
Here are some pros and cons of each approach:
hexToArrayBuffer
:parseInt 16
:Library Used
There is no explicit library used in the benchmark definition JSON. However, the Uint8Array
class is a built-in JavaScript object, and the parseInt
function with base 16 is also a built-in function.
Special JS Feature/Syntax
No special JavaScript features or syntax are used in this benchmark.
Other Alternatives
Other alternatives for converting hexadecimal strings to arrays or Uint8Arrays include:
fromHex
method of the Uint8Array
class (available in some browsers).hex-to-array-buffer
.libuv
or node-ffi
to perform the conversion.Keep in mind that these alternatives may have different performance characteristics and trade-offs, depending on the specific use case and requirements.