Skip to content

Commit

Permalink
Improve the speed of coins.String() (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
ValarDragon committed Nov 19, 2021
1 parent 9398f53 commit 1125dbf
Showing 1 changed file with 10 additions and 5 deletions.
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 @@ -190,13 +190,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

0 comments on commit 1125dbf

Please sign in to comment.