Skip to content

Commit b004ede

Browse files
fjlkielbarry
authored andcommitted
consensus/ethash: reduce keccak hash allocations (ethereum#16857)
Use Read instead of Sum to avoid internal allocations and copying the state. name old time/op new time/op delta CacheGeneration-8 764ms ± 1% 579ms ± 1% -24.22% (p=0.000 n=20+17) SmallDatasetGeneration-8 75.2ms ±12% 60.6ms ±10% -19.37% (p=0.000 n=20+20) HashimotoLight-8 1.58ms ±11% 1.55ms ± 8% ~ (p=0.322 n=20+19) HashimotoFullSmall-8 4.90µs ± 1% 4.88µs ± 1% -0.31% (p=0.013 n=19+18)
1 parent 074bf6b commit b004ede

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

consensus/ethash/algorithm.go

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,25 @@ func calcDatasetSize(epoch int) uint64 {
9494
// reused between hash runs instead of requiring new ones to be created.
9595
type hasher func(dest []byte, data []byte)
9696

97-
// makeHasher creates a repetitive hasher, allowing the same hash data structures
98-
// to be reused between hash runs instead of requiring new ones to be created.
99-
// The returned function is not thread safe!
97+
// makeHasher creates a repetitive hasher, allowing the same hash data structures to
98+
// be reused between hash runs instead of requiring new ones to be created. The returned
99+
// function is not thread safe!
100100
func makeHasher(h hash.Hash) hasher {
101+
// sha3.state supports Read to get the sum, use it to avoid the overhead of Sum.
102+
// Read alters the state but we reset the hash before every operation.
103+
type readerHash interface {
104+
hash.Hash
105+
Read([]byte) (int, error)
106+
}
107+
rh, ok := h.(readerHash)
108+
if !ok {
109+
panic("can't find Read method on hash")
110+
}
111+
outputLen := rh.Size()
101112
return func(dest []byte, data []byte) {
102-
h.Write(data)
103-
h.Sum(dest[:0])
104-
h.Reset()
113+
rh.Reset()
114+
rh.Write(data)
115+
rh.Read(dest[:outputLen])
105116
}
106117
}
107118

0 commit comments

Comments
 (0)