Skip to content

Commit

Permalink
perf: Speedup coins.Sort() when coins is of length 1
Browse files Browse the repository at this point in the history
Coins.Sort() performs a heap allocation, even though sort.Sort() is in place.

This is because the compiler is doing {something} called runtime.convTSlice which internally makes a copy of the entire slice.

We should ideally find a solution that avoids this malloc for every Coins.Sort() of all sizes, but just eliminating it for slices of length <= 1 is already a big win, as Sort's are used throughout the Add and Sub logic.
  • Loading branch information
ValarDragon authored Dec 22, 2023
1 parent 44be021 commit 805b630
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion types/coin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down

0 comments on commit 805b630

Please sign in to comment.