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

types: intern AccAddress.String() to gut wasted expensive recomputations #8694

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"strings"
"sync"

yaml "gopkg.in/yaml.v2"

Expand Down Expand Up @@ -236,8 +237,28 @@ func (aa AccAddress) Bytes() []byte {
return aa
}

// AccAddress.String() is expensive and if unoptimized dominantly showed up in profiles,
// yet has no mechanisms to trivially cache the result given that AccAddress is a []byte type.
// With the string interning below, we are able to achieve zero cost allocations for string->[]byte
// because the Go compiler recognizes the special case of map[string([]byte)] when used exactly
// in that pattern. See https://github.com/cosmos/cosmos-sdk/issues/8693.
var addMu sync.Mutex
var addrStrMemoize = make(map[string]string)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should there be some sort of eviction of the memoized addresses


// String implements the Stringer interface.
func (aa AccAddress) String() string {
func (aa AccAddress) String() (str string) {
addMu.Lock()
defer addMu.Unlock()

if str, ok := addrStrMemoize[string(aa)]; ok {
return str
}

// Otherwise cache it for later memoization.
defer func() {
addrStrMemoize[string(aa)] = str
}()

odeke-em marked this conversation as resolved.
Show resolved Hide resolved
if aa.Empty() {
return ""
}
Expand Down