From bdfd23af0d2f8f7fe12ae3cda72bcd7424bd761a Mon Sep 17 00:00:00 2001 From: ValarDragon Date: Sat, 28 Aug 2021 15:48:17 -0400 Subject: [PATCH 1/2] Speedup coins.AmountOf() by removing many regex calls --- types/coin.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types/coin.go b/types/coin.go index 3cfc58b7b3bb..e8fe7a5f8781 100644 --- a/types/coin.go +++ b/types/coin.go @@ -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() @@ -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) } } } From 17f65a878848146256be59b17bc0e77db7ca239b Mon Sep 17 00:00:00 2001 From: ValarDragon Date: Sat, 28 Aug 2021 15:56:06 -0400 Subject: [PATCH 2/2] Add Changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3ee0f67bd58..3256ead4c152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (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