-
Notifications
You must be signed in to change notification settings - Fork 17
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
fix: fix slice init length #1397
base: main
Are you sure you want to change the base?
Conversation
Actually, since append is used, there is no need for 'make'. We can just define the slice as |
Modified, please review again |
func printPrettierDelegates(delegates [][]byte) []string {
prettierDelegates := make([]string, len(delegates))
for _, delegate := range delegates {
prettierDelegates = append(prettierDelegates, ethcommon.BytesToAddress(delegate).String())
}
... This code creates a slice
func printPrettierDelegates(delegates [][]byte) []string {
prettierDelegates := []string{}
for _, delegate := range delegates {
prettierDelegates = append(prettierDelegates, ethcommon.BytesToAddress(delegate).String())
}
... This version works correctly but doesn't pre-allocate any capacity. For a small number of delegates, this isn't an issue, but if delegates is large, it can cause multiple memory allocations as the slice grows.
func printPrettierDelegates(delegates [][]byte) []string {
prettierDelegates := make([]string, 0, len(delegates)) // Capacity set to length of delegates
for _, delegate := range delegates {
prettierDelegates = append(prettierDelegates, ethcommon.BytesToAddress(delegate).String())
}
... This version is more efficient while being correct. It avoids unnecessary re-allocations by pre-allocating the right amount of capacity while still using append to add elements in order. You have enough space for all elements, avoiding multiple memory allocations and the slice starts with a length of 0, so append adds elements in order without leaving any zero-value entries. |
Signed-off-by: wangjingcun <[email protected]>
Has been modified. In fact, this is the version I first submitted. This can avoid memory overhead caused by multiple expansion, and there is no problem with the previous part of the element zero value. Thanks for your guidance and please review again. |
Pull Request Test Coverage Report for Build 11720758074Details
💛 - Coveralls |
The intention here should be to initialize a slice with a capacity of
len(delegates)
rather than initializing the length of this slice.The online demo: https://go.dev/play/p/q1BcVCmvidW