slices: amortize allocations in Insert #54948
Labels
FeatureRequest
Issues asking for a new feature that does not need a proposal.
FrozenDueToAge
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Performance
Milestone
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
I benchmarked calling slices.Insert at index 0 in a loop: https://gist.github.com/Deleplace/0544f0681912348666ee48e2d55bc58d
What did you expect to see?
I expected
slices.Insert
to have a total cost O(N^2) to insert N element one by one (because it needs to shift all elements to the right each time), and to perform only O(log N) memory allocation operations, likeappend
.What did you see instead?
slices.Insert
is O(N^2) but its cost is dominated by memory allocation. It does O(N) allocs.The current strategy when inserting 1 element is to grow the slice capacity by only 1, as corroborated by the current implementation, this comment and this tweet.
I suggest we implement an allocation strategy similar to
append
's strategy that implements a dynamic array, for 2 reasons:slices.Insert
to insert many elements, but we can't expect them all to be available all at once, or to be all inserted at the same index.append
in mind.The text was updated successfully, but these errors were encountered: