Skip to content

Suggestion to avoid allocations by passing delegate directly or lambda #3761

@jnm2

Description

@jnm2

The aim of dotnet/roslyn#40364 is simplification, while the aim of this alternative is performance.

denotes where the suggestion span would be and _ denotes the spans that would be faded as unnecessary.

class C
{
    // Changed to an instance method because of https://github.com/dotnet/roslyn/pull/58288
    bool IsEven(int x) => x % 2 == 0;

    void Example1()
    {
        // 💡 Avoid allocation by replacing method group with lambda
        //                          ↓↓↓↓↓↓
        _ = new[] { 1, 2, 3 }.Where(IsEven);

        // 🛠 Fix result:
        _ = new[] { 1, 2, 3 }.Where(n => IsEven(n));
    }

    void Example2()
    {
        var neverReassigned = new Func<int, bool>(IsEven);

        // 💡 Avoid allocation by replacing lambda with delegate
        //                          _____↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓___
        _ = new[] { 1, 2, 3 }.Where(n => neverReassigned(n));

        // 💡 Avoid allocation by replacing lambda with delegate
        //                          _____↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓__________
        _ = new[] { 1, 2, 3 }.Where(n => neverReassigned.Invoke(n));

        // 💡 Avoid allocation by replacing Invoke method group with delegate
        //                          ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓_______
        _ = new[] { 1, 2, 3 }.Where(neverReassigned.Invoke);


        // 🛠 Fix result:
        _ = new[] { 1, 2, 3 }.Where(neverReassigned);
    }

    void Example3()
    {
        var reassigned = new Func<int, bool>(IsEven);

        // No diagnostic
        _ = new[] { 1, 2, 3 }.Where(n => reassigned.Invoke(n));

        // 💡 Avoid allocation by replacing Invoke method group with delegate
        //                          ↓↓↓↓↓↓↓↓↓↓_______
        _ = new[] { 1, 2, 3 }.Where(reassigned.Invoke);

        reassigned = n => !IsEven(n);


        // 🛠 Fix result:
        _ = new[] { 1, 2, 3 }.Where(reassigned);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions