Skip to content

Commit e1d2e0a

Browse files
authored
Prov: Improve performance of GetAllBalances and GetAccountsBalances. (#616)
* Improve performance of GetAllBalances and GetAccountsBalances. * Add changelog entry.
1 parent b7c4abd commit e1d2e0a

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ Ref: https://keepachangelog.com/en/1.0.0/
3838

3939
## [Unreleased Provenance]
4040

41-
* nothing
41+
### Improvments
42+
43+
* [#616](https://github.com/provenance-io/cosmos-sdk/pull/616) Provenance: Improve performance of the `GetAllBalances` and `GetAccountsBalances` keeper methods.
4244

4345
---
4446

x/bank/keeper/view.go

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -131,34 +131,33 @@ func (k BaseViewKeeper) Logger() log.Logger {
131131
// GetAllBalances returns all the account balances for the given account address.
132132
func (k BaseViewKeeper) GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins {
133133
balances := sdk.NewCoins()
134+
// Prov customization can be removed with a version that has https://github.com/cosmos/cosmos-sdk/pull/24148.
134135
k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool {
135-
balances = balances.Add(balance)
136+
balances = append(balances, balance)
136137
return false
137138
})
138139

139-
return balances.Sort()
140+
return balances
140141
}
141142

142143
// GetAccountsBalances returns all the accounts balances from the store.
143144
func (k BaseViewKeeper) GetAccountsBalances(ctx context.Context) []types.Balance {
144145
balances := make([]types.Balance, 0)
145-
mapAddressToBalancesIdx := make(map[string]int)
146146

147147
k.IterateAllBalances(ctx, func(addr sdk.AccAddress, balance sdk.Coin) bool {
148-
idx, ok := mapAddressToBalancesIdx[addr.String()]
149-
if ok {
150-
// address is already on the set of accounts balances
151-
balances[idx].Coins = balances[idx].Coins.Add(balance)
152-
balances[idx].Coins.Sort()
148+
addrStr := addr.String()
149+
if len(balances) > 0 && balances[len(balances)-1].Address == addrStr {
150+
// Same address as last entry = add the coin to it.
151+
balances[len(balances)-1].Coins = append(balances[len(balances)-1].Coins, balance)
153152
return false
154153
}
155154

155+
// New address = new entry.
156156
accountBalance := types.Balance{
157-
Address: addr.String(),
157+
Address: addrStr,
158158
Coins: sdk.NewCoins(balance),
159159
}
160160
balances = append(balances, accountBalance)
161-
mapAddressToBalancesIdx[addr.String()] = len(balances) - 1
162161
return false
163162
})
164163

0 commit comments

Comments
 (0)