Skip to content

Avoid enumeration allocation via interface #4505

@benaadams

Description

@benaadams

Can the Jitter/runtime resolve down one level when calling foreach on an interface where a strongly typed enumerator exists? Or otherwise prevent boxing; can always just be for the foreach case.

There may need to be a pattern; for example the Interface enumerator returning result of call to strongly typed Enumerator.

Enumerating Dictionary doesn't allocate; however casting to an IDictionary then enumerating allocates. Shouldn't it follow the same code path as Dictionary?

var dict = new Dictionary<string, string>();
var idict = (IDictionary<string, string>)dict;

for (var i = 0; i < 1000000; i++)
{
    // Doesn't allocate
    foreach (var item in dict)
    {
        ;
    }
}

for (var i = 0; i < 1000000; i++)
{
    // Allocates 998k
    foreach (var item in idict)
    {
        ;
    }
}

allocs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions