From bd04173012d282a0ad1f4b0d891b698a67265c48 Mon Sep 17 00:00:00 2001 From: Dev Ojha Date: Sat, 23 Dec 2023 04:15:25 -0600 Subject: [PATCH] perf: Speedup coins.Sort() when coins is of length 1 (#18875) --- CHANGELOG.md | 1 + types/coin.go | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 943f05034c4..eccc2b708a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements +* (types) [#18875](https://github.com/cosmos/cosmos-sdk/pull/18875) Speedup coins.Sort() if len(coins) <= 1 * (client/keys) [#18745](https://github.com/cosmos/cosmos-sdk/pull/18745) Improve ` keys export` and ` keys mnemonic` by adding --yes option to skip interactive confirmation. * (client/keys) [#18743](https://github.com/cosmos/cosmos-sdk/pull/18743) Improve ` keys add -i` by hiding inputting of bip39 passphrase. * (client/keys) [#18703](https://github.com/cosmos/cosmos-sdk/pull/18703) Improve ` keys add` and ` keys show` by checking whether there are duplicate keys in the multisig case. diff --git a/types/coin.go b/types/coin.go index 1ca5eeb44ca..4b47401a096 100644 --- a/types/coin.go +++ b/types/coin.go @@ -823,7 +823,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 }