Make ArrayBuilder stack allocate the first 16 entries for less heap allocations#120439
Make ArrayBuilder stack allocate the first 16 entries for less heap allocations#120439Henr1k80 wants to merge 3 commits intodotnet:mainfrom
Conversation
| internal struct ArrayBuilder<T> | ||
| { | ||
| private const int DefaultCapacity = 4; | ||
| private InlineArray16<T> _stackAllocatedBuffer = default; |
There was a problem hiding this comment.
Anywhere ArrayBuilder<T> is used as a field on a class, this is going to increase the size of that class' allocation by 16 Ts.
There was a problem hiding this comment.
Yeah, that's a problem.
But it is not used as a field currently. Could there be a warning in <remarks>, or is it a no go?
It could also be made a separate struct if it is useful? E.g. StackArrayBuilder<T>
There was a problem hiding this comment.
Could making it a ref struct could solve it for classes?
There was a problem hiding this comment.
There was a problem hiding this comment.
Yeah, that shoots it down @jkotas, at least modifying ArrayBuilder<T>
I did not find these when opening sfx.slnx, so I guess there is more to it than that.
There was a problem hiding this comment.
Does it make sense to make a ref struct StackArrayBuilder<T>?
|
Oh, I can also see that some tests using reflection fails now, probably because of the |
|
Ok, I have changed it to a draft proposal of new stack allocating ref structs for building arrays. One example of a simple fixed max stack size (8), where it fails hard, if you over go over the size. Another one, where growing is allowed, if max expected size is not known, or if growing, beyond expected capacity, is rare . I have written unit tests, but I do not know where to place them. |
|
Draft Pull Request was automatically closed for 30 days of inactivity. Please let us know if you'd like to reopen it. |
In #120336 I was suggested to add the improvements to the already existing
ArrayBuilder<T>and use that in that PR.The heap allocated buffer will only be allocated if capacity is above the 16 stack allocated capacity.
In cases where there is no conditional adds and capacity is known, it will not make a difference, as the previous internal buffer will just be returned.
But in these cases, an array with correct capacity and an index could just be used instead of the
ArrayBuilder<T>.I have removed the unused
Buffergetter.