Skip to content

Commit

Permalink
Speedup coins.AmountOf() by removing many regex calls
Browse files Browse the repository at this point in the history
  • Loading branch information
ValarDragon committed Aug 28, 2021
1 parent e9adb9e commit bdfd23a
Showing 1 changed file with 8 additions and 2 deletions.
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 bdfd23a

Please sign in to comment.