Skip to content

Commit

Permalink
Add base58 benchmark, tried to speed code a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
moncho committed Sep 18, 2017
1 parent 1bd1299 commit 59302d0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
16 changes: 11 additions & 5 deletions bitcoin/bitcoin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -37,23 +37,29 @@ 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
for _, i := range b {
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.
Expand Down
17 changes: 17 additions & 0 deletions bitcoin/bitcoinbench_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 59302d0

Please sign in to comment.