Avoid building DebugFinalizableAsyncStateMachineBox unless necessary (#20318)
authorStephen Toub <stoub@microsoft.com>
Tue, 9 Oct 2018 18:52:34 +0000 (14:52 -0400)
committerGitHub <noreply@github.com>
Tue, 9 Oct 2018 18:52:34 +0000 (14:52 -0400)
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs

index fc37ca7..acfbd14 100644 (file)
@@ -485,7 +485,7 @@ namespace System.Runtime.CompilerServices
             // object's identity to track this specific builder/state machine.  As such, we proceed to
             // overwrite whatever's there anyway, even if it's non-null.
             var box = AsyncMethodBuilderCore.TrackAsyncMethodCompletion ?
-                new DebugFinalizableAsyncStateMachineBox<TStateMachine>() :
+                CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>() :
                 new AsyncStateMachineBox<TStateMachine>();
             m_task = box; // important: this must be done before storing stateMachine into box.StateMachine!
             box.StateMachine = stateMachine;
@@ -493,6 +493,12 @@ namespace System.Runtime.CompilerServices
             return box;
         }
 
+        // Avoid forcing the JIT to build DebugFinalizableAsyncStateMachineBox<TStateMachine> unless it's actually needed.
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        private static AsyncStateMachineBox<TStateMachine> CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>()
+            where TStateMachine : IAsyncStateMachine =>
+            new DebugFinalizableAsyncStateMachineBox<TStateMachine>();
+
         /// <summary>
         /// Provides an async state machine box with a finalizer that will fire an EventSource
         /// event about the state machine if it's being finalized without having been completed.
@@ -617,7 +623,7 @@ namespace System.Runtime.CompilerServices
         {
             Debug.Assert(m_task == null);
             return (m_task = AsyncMethodBuilderCore.TrackAsyncMethodCompletion ?
-                new DebugFinalizableAsyncStateMachineBox<IAsyncStateMachine>() :
+                CreateDebugFinalizableAsyncStateMachineBox<IAsyncStateMachine>() :
                 new AsyncStateMachineBox<IAsyncStateMachine>());
         }