KEMBAR78
Config generator emits lambdas for error path that force allocation on success path · Issue #90971 · dotnet/runtime · GitHub
Skip to content

Config generator emits lambdas for error path that force allocation on success path #90971

@stephentoub

Description

@stephentoub

Consider a method like:

internal class C1
{
    public int Value { get; set; }

    public static void M(IConfiguration configuration, C1 c) => configuration.Bind(c);
}

That results in this BindCore method being emitted:

        public static void BindCore(IConfiguration configuration, ref C1 obj, BinderOptions? binderOptions)
        {
            ValidateConfigurationKeys(typeof(C1), s_configKeys_C1, configuration, binderOptions);

            if (configuration["Value"] is string value15)
            {
                obj.Value = ParseInt(value15, () => configuration.GetSection("Value").Path);
            }
        }

That ParseInt call closes over the configuration parameter, which means the compiler will lift the configuration parameter to a display class and generate code like this:

public static void BindCore(IConfiguration configuration, ref C1 obj, [Nullable(2)] BinderOptions binderOptions)
{
	<>c__DisplayClass15_0 <>c__DisplayClass15_ = new <>c__DisplayClass15_0();
	<>c__DisplayClass15_.configuration = configuration;
	ValidateConfigurationKeys(typeof(C1), s_configKeys_C1, <>c__DisplayClass15_.configuration, binderOptions);
	string value22 = <>c__DisplayClass15_.configuration["Value"];
	if (value22 != null)
	{
		obj.Value = ParseInt(value22, new Func<string>(<>c__DisplayClass15_.<BindCore>b__0));
	}
}

That means we're allocating a <>c__DisplayClass15_0 object on all invocation, even though that lambda causing the closure is only used by ParseInt when parsing fails and an exception is thrown and caught.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority:2Work that is important, but not critical for the releasearea-Extensions-Configurationhelp wanted[up-for-grabs] Good issue for external contributorsin-prThere is an active PR which will close this issue when it is mergedsource-generatorIndicates an issue with a source generator featuretenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions