Skip to content

Commit

Permalink
Make syncing the L2 chain ~twice as fast (ethereum#243)
Browse files Browse the repository at this point in the history
* add memoize to MethodById

* switch to reader writer lock
  • Loading branch information
geohot authored Mar 3, 2021
1 parent 40bd0ce commit 515ea43
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions accounts/abi/abi.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"encoding/json"
"fmt"
"io"
"sync"

"github.com/ethereum/go-ethereum/common"
)
Expand Down Expand Up @@ -162,14 +163,28 @@ func (abi *ABI) UnmarshalJSON(data []byte) error {
return nil
}

var methodCache map[[4]byte]*Method = make(map[[4]byte]*Method)
var methodCacheLock sync.RWMutex

// MethodById looks up a method by the 4-byte id
// returns nil if none found
func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
if len(sigdata) < 4 {
return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
}

var sigdata4 [4]byte = [4]byte{sigdata[0], sigdata[1], sigdata[2], sigdata[3]}
if methodCache[sigdata4] != nil {
methodCacheLock.RLock()
defer methodCacheLock.RUnlock()
return methodCache[sigdata4], nil
}

for _, method := range abi.Methods {
if bytes.Equal(method.ID(), sigdata[:4]) {
methodCacheLock.Lock()
methodCache[sigdata4] = &method
methodCacheLock.Unlock()
return &method, nil
}
}
Expand Down

0 comments on commit 515ea43

Please sign in to comment.