JasonBock / Rocks

A mocking library based on the Compiler APIs (Roslyn + Mocks)
MIT License
263 stars 20 forks source link

Reduce the Capacity of the Handler List Creation #293

Closed JasonBock closed 10 months ago

JasonBock commented 10 months ago

Describe the solution you'd like

Whenever I create a handler list, I use the default size (which is 4 as of .NET 8....I think it's been that way for a while):

private readonly global::System.Collections.Generic.List<global::Rocks.Handler> @handlers0 = new();

I think the typical usage of a mock is to only set one or two expectations. So, maybe the correct thing to do is to set them all to 2:

private readonly global::System.Collections.Generic.List<global::Rocks.Handler> @handlers0 = new(2);

Maybe even setting it to 1 would be ideal. Not sure. Maybe having an optional parameter for the expectation creation would allow users to set the capacity size, but....I'm not sure that's worth it.

JasonBock commented 10 months ago

I just realized that if you don't provide a capacity, then the array is set to one that has zero capacity. So....I'm not sure if my idea will help - it may actually hurt, though....it might help because, again, I'm betting that most mock usage will only set one or two expectations, so changing the default capacity size could help on a resize.

JasonBock commented 10 months ago

Actually, setting the initial capacity to a value like 2 isn't what I want, because that would actually allocated an array of length 2. What I might do is set all of the lists as a nullable type, like this:

private readonly global::System.Collections.Generic.List<global::Rocks.Handler>; @handlers0;

When an expectation is set, I'd make a check to create the list if it's not created (this won't be thread-safe):

if (this.Expectations.handlers0 is null ) { this.Expectations.handlers0 = new(); }
this.Expectations.handlers0.Add(handler);
return new(handler);

This would mean we'd have to do null checks when we look at the .Count values:

if (this.Expectations.handlers0?.Count > 0)

We also need to check for this in .Verify(). I should do this together with #292