Skip to content

Unnecessary copy generated in async code #21139

@mikedn

Description

@mikedn

Compile the following method using Visual Studio 2017 15.3.0 Preview 5.0 and inspect the generated IL code:

static async Task Test() => await Task.CompletedTask;
.locals init(
    [0] valuetype Program/'<Test>d__6',
    [1] valuetype[System.Private.CoreLib] System.Runtime.CompilerServices.AsyncTaskMethodBuilder
)
IL_0000: ldloca.s 0
IL_0002: call valuetype[System.Private.CoreLib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder[System.Private.CoreLib] System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Create()
IL_0007: stfld valuetype[System.Private.CoreLib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<Test>d__6'::'<>t__builder'
IL_000c: ldloca.s 0
IL_000e: ldc.i4.m1
IL_000f: stfld int32 Program/'<Test>d__6'::'<>1__state'
IL_0014: ldloc.0
IL_0015: ldfld valuetype[System.Private.CoreLib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<Test>d__6'::'<>t__builder'
IL_001a: stloc.1
IL_001b: ldloca.s 1
IL_001d: ldloca.s 0
IL_001f: call instance void[System.Private.CoreLib] System.Runtime.CompilerServices.AsyncTaskMethodBuilder::Start<valuetype Program/'<Test>d__6'>(!!0&)
IL_0024: ldloca.s 0
IL_0026: ldflda valuetype[System.Private.CoreLib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program/'<Test>d__6'::'<>t__builder'
IL_002b: call instance class [System.Private.CoreLib]System.Threading.Tasks.Task[System.Private.CoreLib] System.Runtime.CompilerServices.AsyncTaskMethodBuilder::get_Task()

Note that a copy of the builder is created and Start is invoked on that and not on the builder in t__builder.

Start doesn't use any members of the builder so this doesn't impact correctness but the generated code is larger, slower and uses more stack space than it should.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions