Optimise u8aToHex function (32% of original time) (#265)

This commit is contained in:
Jaco Greeff
2018-12-06 12:04:08 +01:00
committed by GitHub
parent e71d7a30d3
commit 2be211cc98
2 changed files with 8 additions and 2 deletions
+1
View File
@@ -1,2 +1,3 @@
exclude_patterns:
- "**/*.spec.js"
- "docs/**/*.js"
+7 -2
View File
@@ -2,6 +2,8 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
const ALPHABET = '0123456789abcdef';
/**
* @name u8aToHex
* @signature u8aToHex (value?: UInt8Array): string
@@ -34,7 +36,10 @@ export default function u8aToHex (value?: Uint8Array | null, bitLength: number =
return `${u8aToHex(value.subarray(0, halfLength), -1, isPrefixed)}…${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`;
}
return value.reduce((result, item) => {
return result + `0${item.toString(16)}`.slice(-2);
// based on comments in https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex and
// implementation in http://jsben.ch/Vjx2V - optimisation here suggests that a forEach loop is faster
// than reduce as well (clocking at in 90% of the reduce speed with tweaking in the playpen above)
return value.reduce((result, value) => {
return result + ALPHABET[value >> 4] + ALPHABET[value & 15];
}, prefix);
}