From 59302d0650fd1ece63f4123694dac2568d5c9760 Mon Sep 17 00:00:00 2001 From: moncho Date: Mon, 18 Sep 2017 16:29:20 +0200 Subject: [PATCH] Add base58 benchmark, tried to speed code a bit --- bitcoin/bitcoin.go | 16 +++++++++++----- bitcoin/bitcoinbench_test.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 bitcoin/bitcoinbench_test.go diff --git a/bitcoin/bitcoin.go b/bitcoin/bitcoin.go index 0e00031..f9720f0 100644 --- a/bitcoin/bitcoin.go +++ b/bitcoin/bitcoin.go @@ -9,7 +9,7 @@ import ( const ( //Base58BitcoinSymbolChart see https://en.bitcoin.it/wiki/Base58Check_encoding Base58BitcoinSymbolChart = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - base58BitcoinSymbolChartIdx0 = "1" + base58BitcoinSymbolChartIdx0 = '1' //PrivateKeyVersionPrefix is the prefix of WIF encoded strings //see https://en.bitcoin.it/wiki/List_of_address_prefixes @@ -37,12 +37,12 @@ func b58encode(b []byte) string { //Convert bytes to big integer x := new(big.Int).SetBytes(b) r := new(big.Int) - var result string + result := make([]byte, 0, len(b)*136/100) for x.Cmp(zero) > 0 { // x, r = (x / 58, x % 58) x, r = x.QuoRem(x, base, r) - result = string(Base58BitcoinSymbolChart[r.Int64()]) + result + result = append(result, Base58BitcoinSymbolChart[r.Int64()]) } // leading zero bytes @@ -50,10 +50,16 @@ func b58encode(b []byte) string { if i != 0 { break } - result = base58BitcoinSymbolChartIdx0 + result + result = append(result, base58BitcoinSymbolChartIdx0) } - return result + // reverse + rlen := len(result) + for i := 0; i < rlen/2; i++ { + result[i], result[rlen-1-i] = result[rlen-1-i], result[i] + } + + return string(result) } //Base58CheckEncode encodes the given byte array in Bitcoin into human-typable strings. diff --git a/bitcoin/bitcoinbench_test.go b/bitcoin/bitcoinbench_test.go new file mode 100644 index 0000000..85577bf --- /dev/null +++ b/bitcoin/bitcoinbench_test.go @@ -0,0 +1,17 @@ +package bitcoin + +import ( + "bytes" + "testing" +) + +func BenchmarkBase58Encode(b *testing.B) { + b.StopTimer() + data := bytes.Repeat([]byte{0xff}, 5000) + b.SetBytes(int64(len(data))) + b.StartTimer() + + for i := 0; i < b.N; i++ { + b58encode(data) + } +}