Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

all: can avoid the use of bytes.Buffer and .Next simply by reslicing, since bytes.NewBuffer has an allocation and CPU time cost #298

Open
odeke-em opened this issue Mar 15, 2024 · 0 comments

Comments

@odeke-em
Copy link

odeke-em commented Mar 15, 2024

Summary of Bug

Noticed throughout the repository that there is this pattern

keyPair := bytes.NewBuffer(iter.Key())
keyPair.Next(1) // trim prefix byte
blockHeight := sdk.BigEndianToUint64(keyPair.Next(8))
id := keyPair.Next(32)
val := sdk.ValAddress(keyPair.Next(20))
contract := common.BytesToAddress(keyPair.Bytes())

Suggestion

Simply use byte slicing which can be made so much clearer and removes unnecessary expenses

		key := iter.Key()[1:]
		blockHeight, key := sdk.BigEndianToUint64(key[:8]), key[8:]
		id, key := key[:32], key[32:]
		val, key := sdk.ValAddress(key[:20]), key[20:]
		contract := common.BytesToAddress(key[:])

and you'll notice performance improvements from not being heavy handed with all these bytes.NewBuffer allocations

Other spots

keyPair := bytes.NewBuffer(iter.Key())
keyPair.Next(1) // trim prefix byte
keyPair.Next(8) // trim chain ID
blockHeight := binary.BigEndian.Uint64(keyPair.Next(8))
contractAddress := common.BytesToAddress(keyPair.Next(20)) // contract

keyPair := bytes.NewBuffer(iter.Key())
keyPair.Next(1) // trim prefix byte
keyPair.Next(8) // trim chain id, it was filtered in the prefix
blockHeight := sdk.BigEndianToUint64(keyPair.Next(8))
id := keyPair.Next(32)
val := sdk.ValAddress(keyPair.Next(20))
contract := common.BytesToAddress(keyPair.Next(20))

keyPair := bytes.NewBuffer(iter.Key())
keyPair.Next(1) // trim prefix byte
id := keyPair.Next(32)

keyPair := bytes.NewBuffer(iter.Key())
keyPair.Next(1) // trim prefix byte
chainID := sdk.BigEndianToUint64(keyPair.Next(8))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant