tbase_encode/base_decode: performance improvement - electrum - Electrum Bitcoin wallet HTML git clone https://git.parazyd.org/electrum DIR Log DIR Files DIR Refs DIR Submodules --- DIR commit 01f94fcf5817be9ff9182bfcda957a8e0e31bf8e DIR parent 369d972aed376a59bb21952afa16b43105724a32 HTML Author: SomberNight <somber.night@protonmail.com> Date: Sun, 8 Dec 2019 06:07:01 +0100 base_encode/base_decode: performance improvement For example, for 50 KB of random data, and base 43, previously, - base_encode took ~38 seconds - base_decode took ~270 seconds now, - base_encode takes ~7.5 seconds - base_decode takes ~6 seconds Diffstat: M electrum/bitcoin.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) --- DIR diff --git a/electrum/bitcoin.py b/electrum/bitcoin.py t@@ -455,8 +455,11 @@ def base_encode(v: bytes, base: int) -> str: if base == 43: chars = __b43chars long_value = 0 - for (i, c) in enumerate(v[::-1]): - long_value += (256**i) * c + power_of_base = 1 + for c in v[::-1]: + # naive but slow variant: long_value += (256**i) * c + long_value += power_of_base * c + power_of_base <<= 8 result = bytearray() while long_value >= base: div, mod = divmod(long_value, base) t@@ -486,11 +489,14 @@ def base_decode(v: Union[bytes, str], length: Optional[int], base: int) -> Optio if base == 43: chars = __b43chars long_value = 0 - for (i, c) in enumerate(v[::-1]): + power_of_base = 1 + for c in v[::-1]: digit = chars.find(bytes([c])) if digit == -1: raise ValueError('Forbidden character {} for base {}'.format(c, base)) - long_value += digit * (base**i) + # naive but slow variant: long_value += digit * (base**i) + long_value += digit * power_of_base + power_of_base *= base result = bytearray() while long_value >= 256: div, mod = divmod(long_value, 256)