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

perf: Improve the speed of coins.String() #10076

Merged
merged 4 commits into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

* (types) [\#10076](https://github.com/cosmos/cosmos-sdk/pull/10076) Significantly speedup and lower allocations for `Coins.String()`.
* (x/bank) [\#10022](https://github.com/cosmos/cosmos-sdk/pull/10022) `BankKeeper.SendCoins` now takes less execution time.
* (deps) [\#9956](https://github.com/cosmos/cosmos-sdk/pull/9956) Bump Tendermint to [v0.34.12](https://github.com/tendermint/tendermint/releases/tag/v0.34.12).
* (cli) [\#9856](https://github.com/cosmos/cosmos-sdk/pull/9856) Overwrite `--sequence` and `--account-number` flags with default flag values when used with `offline=false` in `sign-batch` command.
Expand Down
15 changes: 10 additions & 5 deletions types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func NewInt64Coin(denom string, amount int64) Coin {

// String provides a human-readable representation of a coin
func (coin Coin) String() string {
return fmt.Sprintf("%v%v", coin.Amount, coin.Denom)
return fmt.Sprintf("%v%s", coin.Amount, coin.Denom)
}

// Validate returns an error if the Coin has a negative amount or if
Expand Down Expand Up @@ -185,13 +185,18 @@ func (coins Coins) MarshalJSON() ([]byte, error) {
func (coins Coins) String() string {
if len(coins) == 0 {
return ""
} else if len(coins) == 1 {
return coins[0].String()
}

out := ""
for _, coin := range coins {
out += fmt.Sprintf("%v,", coin.String())
// Build the string with a string builder
var out strings.Builder
for _, coin := range coins[:len(coins)-1] {
out.WriteString(coin.String())
out.WriteByte(',')
}
return out[:len(out)-1]
out.WriteString(coins[len(coins)-1].String())
return out.String()
}

// Validate checks that the Coins are sorted, have positive amount, with a valid and unique
Expand Down