perf: Speedup coins.AmountOf() by removing many regex calls (#10021)
This commit is contained in:
parent
eb0113e4bc
commit
ed35bfdf52
@ -91,6 +91,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
|
||||
* (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.
|
||||
* (types) [\#10021](https://github.com/cosmos/cosmos-sdk/pull/10021) Speedup coins.AmountOf(), by removing many intermittent regex calls.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
|
||||
@ -522,7 +522,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()
|
||||
@ -535,15 +540,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user