Skip to content

Method group allocates when it shouldn't #33747

@smoogipoo

Description

@smoogipoo

The following code:

[MemoryDiagnoser]
public class MethodGroupBenchmarks
{
    [Benchmark]
    public int ByMethodGroup()
    {
        int res = 0;

        for (int i = 0; i < 1000; i++)
            res += doSomething(getValue);

        return res;
    }

    [Benchmark]
    public int ByDelegate()
    {
        int res = 0;

        for (int i = 0; i < 1000; i++)
            res += doSomething(v => getValue(v));

        return res;
    }

    private static int doSomething(Func<int, int> del) => 0;

    private static int getValue(int v) => 0;
}

Outputs:

Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
ByMethodGroup 9,006.7 ns 71.83 ns 67.19 ns 12.2375 - - 64000 B
ByDelegate 546.7 ns 1.12 ns 0.94 ns - - - -

The delegate generated by the by-method-group form is allocated every time, even though it's functionally identical to the by-delegate form.

Metadata

Metadata

Assignees

No one assigned

    Labels

    untriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions