Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leaking slice capacity #360

Closed
wants to merge 1 commit into from

Conversation

rubvs
Copy link
Contributor

@rubvs rubvs commented Sep 5, 2024

The slicing operation in Reslice using slice[:n] creates a n-length slice. However, its capacity remains the same as the initial slice. The remaining elements are still allocated in memory. The backing array of the slice still contains n-elements after the slicing operation.

As a result, the remaining space won’t be reclaimed by the GC, and we can keep a large backing array despite using only a few elements.

This change is really only practical when working with large slices. However, I'm deducing with my limit contextual understanding, that optimization is the purpose of this reslicing function.

@rubvs rubvs requested a review from a team as a code owner September 5, 2024 12:25
@obltmachine obltmachine added the safe-to-test Changes are safe to run in the CI label Sep 5, 2024
@rubvs rubvs requested a review from lahsivjar September 5, 2024 12:28
Comment on lines +30 to +32
res := make(Slice, n)
copy(res, slice[:n])
return res
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can create multiple allocations of slice (one in Grow and the other one which we are doing here). IIANM, the whole point of this function was to reduce allocation and GC (even when the capacity is higher) so I don't think this change is needed. OTOH, now that we are moving away from pooling, we might not even require Reslice but that would be a bigger change overall.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I see. Thanks. I'll close this.

@rubvs rubvs closed this Sep 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
safe-to-test Changes are safe to run in the CI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants