From fc75bbc53509295f3253c383ba121d5e521c6e32 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Tue, 26 Dec 2023 16:02:48 +0000 Subject: [PATCH] perf: Speedup DecCoin.Sort() when coins is of length 1 (backport #18888) (#18890) Co-authored-by: Dong Lieu <93205232+DongLieu@users.noreply.github.com> Co-authored-by: marbar3778 --- CHANGELOG.md | 1 + types/dec_coin.go | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb6f32119434..defe3f25e94a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements +* (types) [#18888](https://github.com/cosmos/cosmos-sdk/pull/18888) Speedup DecCoin.Sort() if len(coins) <= 1 * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. * (server) [#18478](https://github.com/cosmos/cosmos-sdk/pull/18478) Add command flag to disable colored logs. diff --git a/types/dec_coin.go b/types/dec_coin.go index 42ff885d58a6..1b515eac9c15 100644 --- a/types/dec_coin.go +++ b/types/dec_coin.go @@ -611,7 +611,12 @@ func (coins DecCoins) Swap(i, j int) { coins[i], coins[j] = coins[j], coins[i] } // Sort is a helper function to sort the set of decimal coins in-place. func (coins DecCoins) Sort() DecCoins { - sort.Sort(coins) + // sort.Sort(coins) does a costly runtime copy as part of `runtime.convTSlice` + // So we avoid this heap allocation if len(coins) <= 1. In the future, we should hopefully find + // a strategy to always avoid this. + if len(coins) > 1 { + sort.Sort(coins) + } return coins }