Skip to content

Commit bdfd23a

Browse files
committed
Speedup coins.AmountOf() by removing many regex calls
1 parent e9adb9e commit bdfd23a

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

types/coin.go

+8-2
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,12 @@ func (coins Coins) Empty() bool {
517517
// AmountOf returns the amount of a denom from coins
518518
func (coins Coins) AmountOf(denom string) Int {
519519
mustValidateDenom(denom)
520+
return coins.AmountOfNoDenomValidation(denom)
521+
}
520522

523+
// AmountOfNoDenomValidation returns the amount of a denom from coins
524+
// without validating the denomination.
525+
func (coins Coins) AmountOfNoDenomValidation(denom string) Int {
521526
switch len(coins) {
522527
case 0:
523528
return ZeroInt()
@@ -530,15 +535,16 @@ func (coins Coins) AmountOf(denom string) Int {
530535
return ZeroInt()
531536

532537
default:
538+
// Binary search the amount of coins remaining
533539
midIdx := len(coins) / 2 // 2:1, 3:1, 4:2
534540
coin := coins[midIdx]
535541
switch {
536542
case denom < coin.Denom:
537-
return coins[:midIdx].AmountOf(denom)
543+
return coins[:midIdx].AmountOfNoDenomValidation(denom)
538544
case denom == coin.Denom:
539545
return coin.Amount
540546
default:
541-
return coins[midIdx+1:].AmountOf(denom)
547+
return coins[midIdx+1:].AmountOfNoDenomValidation(denom)
542548
}
543549
}
544550
}

0 commit comments

Comments
 (0)