Array will allocate less and little faster when creating RequestDelegateFactoryOptions in CreateRDFOptions
See original GitHub issueIt uses List<string>, which gets assigned to RouteParameterNames
as IEnumerable.
https://github.com/dotnet/aspnetcore/blob/432e6a061f28dda696ba16bc5442328d23b25d93/src/Http/Routing/src/RouteEndpointDataSource.cs#L260
Ran a benchmark with 10 strings of length 6. The results are below.
Another run:
The benchmark code used:
public class Benchmarks
{
private const int Length = 10;
private readonly IReadOnlyCollection<string> _readOnlyCollection = new List<string>() { "param1","param2", "param1","param2", "param1","param2", "param1","param2", "param1","param2"}.AsReadOnly();
[Benchmark]
public void Add10StringsToList()
{
List<string> parameters = new(Length);
foreach (var s in _readOnlyCollection)
{
parameters.Add(s);
}
}
[Benchmark]
public void Add10StringsToArray()
{
var parameters = new string[Length];
var i = 0;
foreach (var s in _readOnlyCollection)
{
parameters[i] = s;
i++;
}
}
}
Issue Analytics
- State:
- Created 8 months ago
- Comments:5 (5 by maintainers)
Top Results From Across the Web
No results found
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
After spending a little bit more time with it, it seems like even array allocation is not required since parameter names are sourced from
IReadOnlyCollection
, andRequestDelegateFactoryOptions
only requiresIEnumerable<string>
so all the allocation can go away. Either using the Linq Select or with the local function that yields.Benchmark results
Benchmark code
Thanks, I understand. I opened the draft PR nervously for you to examine if it will make sense.