From: Kirill Fomichev Date: Wed, 11 Sep 2019 15:58:51 +0000 (+0300) Subject: Use lookup table for faster hex encoding X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=88e321e20920e4fa7897d01e22ce79f9a82b2605;p=buffer.git Use lookup table for faster hex encoding Lookup table faster ~9-12 times than toString('hex') for each byte. See https://github.com/feross/buffer/issues/219 --- diff --git a/index.js b/index.js index 7c018b9..9ec8a35 100644 --- a/index.js +++ b/index.js @@ -1068,7 +1068,7 @@ function hexSlice (buf, start, end) { var out = '' for (var i = start; i < end; ++i) { - out += toHex(buf[i]) + out += hexSliceNewLookupTable[buf[i]] } return out } @@ -1654,11 +1654,6 @@ function base64clean (str) { return str } -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - function utf8ToBytes (string, units) { units = units || Infinity var codePoint @@ -1788,3 +1783,17 @@ function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +var hexSliceNewLookupTable = (function () { + var alphabet = '0123456789abcdef' + var table = new Array(256) + for (var i = 0; i < 16; ++i) { + var i16 = i * 16 + for (var j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})()