From 2be211cc9827070eaa869a81b3aef6465f445365 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Thu, 6 Dec 2018 12:04:08 +0100 Subject: [PATCH] Optimise u8aToHex function (32% of original time) (#265) --- .codeclimate.yml | 1 + packages/util/src/u8a/toHex.ts | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.codeclimate.yml b/.codeclimate.yml index 5d56a3604..bec46efa8 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -1,2 +1,3 @@ exclude_patterns: - "**/*.spec.js" +- "docs/**/*.js" diff --git a/packages/util/src/u8a/toHex.ts b/packages/util/src/u8a/toHex.ts index a585ee874..80f9839bb 100644 --- a/packages/util/src/u8a/toHex.ts +++ b/packages/util/src/u8a/toHex.ts @@ -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); }