Skip to content

Use custom collector to avoid intermediate array allocations #2168

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mgravell
Copy link
Member

Context #2166

List<T> uses initial-size plus doubling, which means that for large result sets you can get multiple arrays, for example for 90 rows you might have arrays with sizes 16, 32, 64, and 128 for 90, with the final result list using the oversized 128-element array, with 90 elements.

This change uses a custom collector for this part - same logic, but it uses the array-pool so that those intermediate arrays are recycled, and the final array is right-sized, i.e. a list with count 90 and capacity 90, and all intermediate arrays reused.

@TimothyMakkison
Copy link

Hey, glad to see someone's working on this.

Have you considered using a stackallocated scratchbuffer for the inital buffer. This pattern is used in both ValueListBuilder and SegmentedArrayBuilder, the latter of which is used internally for Linq for tasks that are very similar to dappers.

// similar to ValueListBuilder
var buffer = new Collector<T>([defaut, default, defaut, default, defaut, default, defaut, default]);

// similar to SegmentedArrayBuilder
Collector<TSource>.ScratchBuffer scratch = default;
Collector<TSource> builder = new Collector<T>(scratch);

@mgravell
Copy link
Member Author

Interesting suggestion. I'll find a moment to look; obviously only suitable for sync path, though.

@mgravell
Copy link
Member Author

Obviously it would also only apply in limited scenarios, i.e. the same rules as unmanaged

@TimothyMakkison
Copy link

TimothyMakkison commented Jul 26, 2025

Interesting suggestion. I'll find a moment to look; obviously only suitable for sync path, though.

Yeah, I thought that it might be suitable for functions that used AsList. I did think that there were areas where ValueListBuilder could be used in Dapper iirc relating to DynamicParameters. I can't imagine the performance gain being large.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants