Skip to content

Commit

Permalink
[hash] optimize hash memory with sync.Pool (#31)
Browse files Browse the repository at this point in the history
* opt hash memory
  • Loading branch information
Liuhaai authored Jan 10, 2022
1 parent a1168bb commit c2c5a13
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions hash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package hash

import (
"encoding/hex"
"sync"

"github.com/ethereum/go-ethereum/crypto"

Expand All @@ -19,6 +20,8 @@ var (
ZeroHash256 = Hash256{}
// ZeroHash160 is 160-bit of all zero
ZeroHash160 = Hash160{}

bufPool sync.Pool
)

type (
Expand All @@ -28,10 +31,20 @@ type (
Hash160 [20]byte
)

func init() {
bufPool = sync.Pool{
New: func() interface{} {
return crypto.NewKeccakState()
},
}
}

// Hash160b returns 160-bit (20-byte) hash of input
func Hash160b(input []byte) Hash160 {
// use sha3 algorithm
digest := crypto.Keccak256(input)
sha3Buf := bufPool.Get().(crypto.KeccakState)
digest := crypto.HashData(sha3Buf, input)
bufPool.Put(sha3Buf)
var hash Hash160
copy(hash[:], digest[12:])
return hash
Expand All @@ -40,10 +53,13 @@ func Hash160b(input []byte) Hash160 {
// Hash256b returns 256-bit (32-byte) hash of input
func Hash256b(input []byte) Hash256 {
// use sha3 algorithm
digest := crypto.Keccak256(input)
var hash Hash256
copy(hash[:], digest)
return hash
sha3Buf := bufPool.Get().(crypto.KeccakState)
sha3Buf.Reset()
sha3Buf.Write(input)
var ret Hash256
sha3Buf.Read(ret[:])
bufPool.Put(sha3Buf)
return ret
}

// BytesToHash256 copies the byte slice into hash
Expand Down

0 comments on commit c2c5a13

Please sign in to comment.