From 23b78d9dd1516ee44d04558d7fd135d5fdea5d70 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Sat, 23 Dec 2023 13:22:51 +0000 Subject: [PATCH] perf: Speedup coins.Sort() when coins is of length 1 (backport #18875) (#18877) Co-authored-by: Dev Ojha Co-authored-by: Julien Robert --- CHANGELOG.md | 1 + types/coin.go | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1f29b4ee3..2aa2aafde9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (x/gov) [#18707](https://github.com/cosmos/cosmos-sdk/pull/18707) Improve genesis validation. * (x/auth/tx) [#18772](https://github.com/cosmos/cosmos-sdk/pull/18772) Remove misleading gas wanted from tx simulation failure log. * (client/tx) [#18852](https://github.com/cosmos/cosmos-sdk/pull/18852) Add `WithFromName` to tx factory. +* (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 ### Bug Fixes diff --git a/types/coin.go b/types/coin.go index 52f351f88f..136295eed2 100644 --- a/types/coin.go +++ b/types/coin.go @@ -820,7 +820,12 @@ var _ sort.Interface = Coins{} // Sort is a helper function to sort the set of coins in-place func (coins Coins) Sort() Coins { - 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 }