Skip to content

Commit

Permalink
perf: Speedup coins.AmountOf() by removing many regex calls (#10021)
Browse files Browse the repository at this point in the history
(cherry picked from commit ed35bfd)

# Conflicts:
#	CHANGELOG.md
  • Loading branch information
ValarDragon authored and mergify-bot committed Sep 16, 2021
1 parent 000c17b commit 8d08bed
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ Ref: https://keepachangelog.com/en/1.0.0/
### Improvements

* (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).
<<<<<<< HEAD
=======
* (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.
* (types) [\#10021](https://github.com/cosmos/cosmos-sdk/pull/10021) Speedup coins.AmountOf(), by removing many intermittent regex calls.
>>>>>>> ed35bfdf5 (perf: Speedup coins.AmountOf() by removing many regex calls (#10021))
### Deprecated

Expand Down
10 changes: 8 additions & 2 deletions types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,12 @@ func (coins Coins) Empty() bool {
// AmountOf returns the amount of a denom from coins
func (coins Coins) AmountOf(denom string) Int {
mustValidateDenom(denom)
return coins.AmountOfNoDenomValidation(denom)
}

// AmountOfNoDenomValidation returns the amount of a denom from coins
// without validating the denomination.
func (coins Coins) AmountOfNoDenomValidation(denom string) Int {
switch len(coins) {
case 0:
return ZeroInt()
Expand All @@ -530,15 +535,16 @@ func (coins Coins) AmountOf(denom string) Int {
return ZeroInt()

default:
// Binary search the amount of coins remaining
midIdx := len(coins) / 2 // 2:1, 3:1, 4:2
coin := coins[midIdx]
switch {
case denom < coin.Denom:
return coins[:midIdx].AmountOf(denom)
return coins[:midIdx].AmountOfNoDenomValidation(denom)
case denom == coin.Denom:
return coin.Amount
default:
return coins[midIdx+1:].AmountOf(denom)
return coins[midIdx+1:].AmountOfNoDenomValidation(denom)
}
}
}
Expand Down

0 comments on commit 8d08bed

Please sign in to comment.