Skip to content

Array will allocate less and little faster when creating RequestDelegateFactoryOptions in CreateRDFOptions #46010

@marafiq

Description

@marafiq

It uses List, which gets assigned to RouteParameterNames as IEnumerable.

var routeParamNames = new List<string>(pattern.Parameters.Count);

Ran a benchmark with 10 strings of length 6. The results are below.
image

Another run:
image

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++;
            }
            
        }
    }

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions