From 297b3e03aa7e870949dc052b547f78d1f38ebdcf Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Fri, 3 Sep 2021 12:46:09 -0400 Subject: [PATCH 1/2] Improve the speed of coins.String() (#30) --- types/coin.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/types/coin.go b/types/coin.go index 3cfc58b7b3bb..facdd56a2206 100644 --- a/types/coin.go +++ b/types/coin.go @@ -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 @@ -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 From d09fd3e40b904127811791670d89cfb0c9af842f Mon Sep 17 00:00:00 2001 From: ValarDragon Date: Fri, 3 Sep 2021 11:56:33 -0500 Subject: [PATCH 2/2] Update Changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fb74788aaca..e17b6e8f4ae2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,6 +86,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.