Skip to content

Use static readonly cached delegates in preference to non-capturing lambdas - #505

Closed
benaadams wants to merge 1 commit into
dotnet:masterfrom
benaadams:cached-delgates
Closed

benaadams wants to merge 1 commit into
dotnet:masterfrom
benaadams:cached-delgates

Conversation

@benaadams

@benaadams benaadams commented Dec 4, 2019 •

Copy link
Copy Markdown
Member

Lambdas show up horribly in stack traces

Changes

<>c:<.cctor>b__4_0(Object):this
<>c:<ExecuteCallbackHandlers>b__44_0(Object):this
<>c:<.cctor>b__10_0(Object):this
<>c:<.cctor>b__8_0(Object):this
<>c:<WaitForCallbackToCompleteAsync>b__50_0(Object):this
<>c:<.cctor>b__23_0(Object):this
<>c:<.cctor>b__56_0(Object):this
<>c:<.cctor>b__6_0(QueueUserWorkItemCallback):this 
<>c:<.cctor>b__26_0(Object):this
<>c:<.cctor>b__17_0(Object):this
<>c:<.cctor>b__274_0(Object):this
<>c:<.cctor>b__17_1(Action):this
<>c:.ctor():this

To

ValueTaskSourceAsTask:InvokeCompletion(Object):this
CancellationTokenSource:ExecuteNodeCallback(Object):this
ThreadPoolWorkQueue:InvokeAsyncStateMachineBox(Object):this
ValueTaskAwaiter:InvokeAction(Object):this
CancellationTokenSource:WhenCallbackCompletes(Object):this
Timer:InvokeCallback(Object):this
CancellationTokenSource:InvokeCallback(Object):this
CancellationTokenSource:LinkedTokenCancel(Object):this
QueueUserWorkItemCallback:InvokeCallback(QueueUserWorkItemCallback):this
ThreadPoolTaskScheduler:StartThread(Object)
SynchronizationContextTaskScheduler:PostCallback(Object)
CancellationToken:InvokeAction(Object):this
AwaitTaskContinuation:InvokeContextCallback(Object):this
Task:InvokeContextCallback(Object):this
AwaitTaskContinuation:InvokeAction(Action):this

The IEnumerator FilterTasksFromWorkItems gets renumbered so it shows up in regressions & improvements

Total bytes of diff: -530 (-0.02% of base)
    diff is an improvement.

Total byte diff includes 134 bytes from reconciling methods
        Base had   22 unique methods,     1828 unique bytes
        Diff had   31 unique methods,     1962 unique bytes

Top file improvements by size (bytes):
        -530 : System.Private.CoreLib.dasm (-0.02% of base)

1 total files with size differences (1 improved, 0 regressed), 0 unchanged.

Top method regressions by size (bytes):
         609 (     8 of base) : System.Private.CoreLib.dasm - ValueTaskSourceAsTask:InvokeCompletion(Object):this (0 base, 2 diff methods)
         342 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:MoveNext():bool:this (0 base, 1 diff methods)
         137 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task>.GetEnumerator():IEnumerator`1:this (0 base, 1 diff methods)
          78 (     8 of base) : System.Private.CoreLib.dasm - CancellationTokenSource:ExecuteNodeCallback(Object):this (0 base, 1 diff methods)
          76 (40.86% of base) : System.Private.CoreLib.dasm - CancellationTokenSource:.cctor()
          59 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:System.IDisposable.Dispose():this (0 base, 1 diff methods)
          54 (     8 of base) : System.Private.CoreLib.dasm - ThreadPoolWorkQueue:InvokeAsyncStateMachineBox(Object):this (0 base, 1 diff methods)
          52 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:.ctor(int):this (0 base, 1 diff methods)
          51 (     8 of base) : System.Private.CoreLib.dasm - AwaitTaskContinuation:.ctor():this (0 base, 1 diff methods)
          44 (16.30% of base) : System.Private.CoreLib.dasm - ValueTaskSourceAsTask:.cctor() (4 methods)

Top method improvements by size (bytes):
        -695 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__4_0(Object):this (4 base, 0 diff methods)
        -667 (-22.89% of base) : System.Private.CoreLib.dasm - <>c:.cctor() (63 base, 48 diff methods)
        -342 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:MoveNext():bool:this (1 base, 0 diff methods)
        -137 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task>.GetEnumerator():IEnumerator`1:this (1 base, 0 diff methods)
         -82 (-7.84% of base) : System.Private.CoreLib.dasm - CancellationTokenSource:ExecuteCallbackHandlers(bool):this
         -78 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<ExecuteCallbackHandlers>b__44_0(Object):this (1 base, 0 diff methods)
         -75 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__10_0(Object):this (2 base, 0 diff methods)
         -59 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:System.IDisposable.Dispose():this (1 base, 0 diff methods)
         -56 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__8_0(Object):this (2 base, 0 diff methods)
         -52 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:.ctor(int):this (1 base, 0 diff methods)

@benaadams
benaadams force-pushed the cached-delgates branch 2 times, most recently from d3dfeb3 to 1d5156c Compare December 4, 2019 15:00
@stephentoub

stephentoub commented Dec 4, 2019 •

Copy link
Copy Markdown
Member

@benaadams, have you measured / examined the perf implications of these changes? The C# compiler doesn't generate a static method for the lambda, but rather an instance method:
https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQhGAzAATZkDCOZA3oWU2Y8wJYB2ALjFBwIYAbCjiRlY/ACYQOggJ4isAHgjAAVjDBcAfGQDOAfU4A3CAGsYGHFgAiMQTADm/HmQC8ZAJIdTFq1gBuViYAByg2YxcYETEMFC8fc0trAApVDS19LiiASnoAX0JCogJSCixqCoYCZhYa9m5eAWErMQlpWQV/FXVNHX0jRL9rOwdnVw89bIndOjJ8oIJ8oA=
based on invocations to delegates to instance methods being faster than those to static methods.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;
using System;

[MemoryDiagnoser]
public class Program
{
    static void Main(string[] args) => BenchmarkSwitcher.FromAssemblies(new[] { typeof(Program).Assembly }).Run(args);

    public static readonly Action<object> s_lambda = o => { };

    public static readonly Action<object> s_static = Static;
    private static void Static(object o) { }

    [Benchmark] public void InvokeLambda() => s_lambda(null);
    [Benchmark] public void InvokeStatic() => s_static(null);
}
Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
InvokeLambda 0.6838 ns 0.0101 ns 0.0095 ns - - - -
InvokeStatic 1.6318 ns 0.0157 ns 0.0146 ns - - - -

I don't know whether it'll matter in these cases, but I'm pointing it out because they are fairly core to the system, and this change isn't purely diagnostic.

@benaadams

benaadams commented Dec 4, 2019 •

Copy link
Copy Markdown
Member Author

Hmm...

Looks like for the lambda it creates a MulticastDelegate.CtorClosed(System.Object, IntPtr) and for the static method it creates a MulticastDelegate.CtorOpened(System.Object, IntPtr, IntPtr)

;     public static readonly Action<object> s_lambda = o => { };
        mov     rcx,offset methodtable(System.Action`1[[System.Object, System.Private.CoreLib]])
        call    CORINFO_HELP_NEWSFAST
        mov     [rbp-8],rax
        mov     rcx,offset <diffable-addr>
        mov     edx,2
        call    CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE
        mov     rdx,offset <diffable-addr>
        mov     rdx,[rdx]
        mov     [rbp-18h],rdx
        mov     rdx,[rbp-18h]
        mov     r8,offset Program+<>c.<.cctor>b__8_0(System.Object)
        mov     rcx,[rbp-8]
        call    System.MulticastDelegate.CtorClosed(System.Object, IntPtr)

        mov     rcx,offset <diffable-addr>
        mov     rdx,[rbp-8]
        call    CORINFO_HELP_CHECKED_ASSIGN_REF

;     public static readonly Action<object> s_static = Static;
        mov     rcx,offset methodtable(System.Action`1[[System.Object, System.Private.CoreLib]])
        call    CORINFO_HELP_NEWSFAST
        mov     [rbp-10h],rax
        mov     r8,offset Program.Static(System.Object)
        mov     rcx,[rbp-10h]
        xor     edx,edx
        mov     r9,offset <diffable-addr>
        call    System.MulticastDelegate.CtorOpened(System.Object, IntPtr, IntPtr)

        mov     rcx,offset <diffable-addr>
        mov     rdx,[rbp-10h]
        call    CORINFO_HELP_CHECKED_ASSIGN_REF

        nop
        lea     rsp,[rbp]
        pop     rbp
        ret

🤔

@benaadams

benaadams commented Dec 4, 2019 •

Copy link
Copy Markdown
Member Author

based on invocations to delegates to instance methods being faster than those to static methods.

Is this because static method delegates involve an extra shuffleThunk? @jkotas

The lambda delegate creation calls this #505 (comment)

private void CtorClosed(object target, IntPtr methodPtr)
{
    if (target == null)
        ThrowNullThisInDelegateToInstance();
    this._target = target;
    this._methodPtr = methodPtr;
}

Whereas the static delgate ctor calls this

private void CtorOpened(object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
    this._target = this;
    this._methodPtr = shuffleThunk;
    this._methodPtrAux = methodPtr;
}
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.

@jkotas

jkotas commented Dec 4, 2019

Copy link
Copy Markdown
Member

Is this because static method delegates involve an extra shuffleThunk? @jkotas

Yep.

@stephentoub stephentoub added the NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) label Dec 5, 2019
@benaadams

Copy link
Copy Markdown
Member Author

Looked at changing how static delegates were invoked; but that looked quite hard. So moved most to instance methods instead.

@benaadams

benaadams commented Dec 6, 2019 •

Copy link
Copy Markdown
Member Author

Updated summary


Lambdas show up horribly in stack traces

Changes

<>c:<.cctor>b__4_0(Object):this
<>c:<ExecuteCallbackHandlers>b__44_0(Object):this
<>c:<.cctor>b__10_0(Object):this
<>c:<.cctor>b__8_0(Object):this
<>c:<WaitForCallbackToCompleteAsync>b__50_0(Object):this
<>c:<.cctor>b__23_0(Object):this
<>c:<.cctor>b__56_0(Object):this
<>c:<.cctor>b__6_0(QueueUserWorkItemCallback):this 
<>c:<.cctor>b__26_0(Object):this
<>c:<.cctor>b__17_0(Object):this
<>c:<.cctor>b__274_0(Object):this
<>c:<.cctor>b__17_1(Action):this
<>c:.ctor():this

To

ValueTaskSourceAsTask:InvokeCompletion(Object):this
CancellationTokenSource:ExecuteNodeCallback(Object):this
ThreadPoolWorkQueue:InvokeAsyncStateMachineBox(Object):this
ValueTaskAwaiter:InvokeAction(Object):this
CancellationTokenSource:WhenCallbackCompletes(Object):this
Timer:InvokeCallback(Object):this
CancellationTokenSource:InvokeCallback(Object):this
CancellationTokenSource:LinkedTokenCancel(Object):this
QueueUserWorkItemCallback:InvokeCallback(QueueUserWorkItemCallback):this
ThreadPoolTaskScheduler:StartThread(Object)
SynchronizationContextTaskScheduler:PostCallback(Object)
CancellationToken:InvokeAction(Object):this
AwaitTaskContinuation:InvokeContextCallback(Object):this
Task:InvokeContextCallback(Object):this
AwaitTaskContinuation:InvokeAction(Action):this

The IEnumerator FilterTasksFromWorkItems gets renumbered so it shows up in regressions & improvements

Total bytes of diff: -530 (-0.02% of base)
    diff is an improvement.

Total byte diff includes 134 bytes from reconciling methods
        Base had   22 unique methods,     1828 unique bytes
        Diff had   31 unique methods,     1962 unique bytes

Top file improvements by size (bytes):
        -530 : System.Private.CoreLib.dasm (-0.02% of base)

1 total files with size differences (1 improved, 0 regressed), 0 unchanged.

Top method regressions by size (bytes):
         609 (     8 of base) : System.Private.CoreLib.dasm - ValueTaskSourceAsTask:InvokeCompletion(Object):this (0 base, 2 diff methods)
         342 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:MoveNext():bool:this (0 base, 1 diff methods)
         137 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task>.GetEnumerator():IEnumerator`1:this (0 base, 1 diff methods)
          78 (     8 of base) : System.Private.CoreLib.dasm - CancellationTokenSource:ExecuteNodeCallback(Object):this (0 base, 1 diff methods)
          76 (40.86% of base) : System.Private.CoreLib.dasm - CancellationTokenSource:.cctor()
          59 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:System.IDisposable.Dispose():this (0 base, 1 diff methods)
          54 (     8 of base) : System.Private.CoreLib.dasm - ThreadPoolWorkQueue:InvokeAsyncStateMachineBox(Object):this (0 base, 1 diff methods)
          52 (     8 of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__7:.ctor(int):this (0 base, 1 diff methods)
          51 (     8 of base) : System.Private.CoreLib.dasm - AwaitTaskContinuation:.ctor():this (0 base, 1 diff methods)
          44 (16.30% of base) : System.Private.CoreLib.dasm - ValueTaskSourceAsTask:.cctor() (4 methods)

Top method improvements by size (bytes):
        -695 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__4_0(Object):this (4 base, 0 diff methods)
        -667 (-22.89% of base) : System.Private.CoreLib.dasm - <>c:.cctor() (63 base, 48 diff methods)
        -342 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:MoveNext():bool:this (1 base, 0 diff methods)
        -137 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:System.Collections.Generic.IEnumerable<System.Threading.Tasks.Task>.GetEnumerator():IEnumerator`1:this (1 base, 0 diff methods)
         -82 (-7.84% of base) : System.Private.CoreLib.dasm - CancellationTokenSource:ExecuteCallbackHandlers(bool):this
         -78 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<ExecuteCallbackHandlers>b__44_0(Object):this (1 base, 0 diff methods)
         -75 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__10_0(Object):this (2 base, 0 diff methods)
         -59 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:System.IDisposable.Dispose():this (1 base, 0 diff methods)
         -56 (-100.00% of base) : System.Private.CoreLib.dasm - <>c:<.cctor>b__8_0(Object):this (2 base, 0 diff methods)
         -52 (-100.00% of base) : System.Private.CoreLib.dasm - <FilterTasksFromWorkItems>d__6:.ctor(int):this (1 base, 0 diff methods)

@stephentoub

Copy link
Copy Markdown
Member

Is this really worth it? Those frames in the stack traces aren't super pretty, but I don't see this providing any more useful information, and the other 99.99999% of lambdas in the world will continue to look the way they do in traces. This is adding a bunch of contortions to the code, and for what.

@benaadams

Copy link
Copy Markdown
Member Author

but I don't see this providing any more useful information

I hear you; and you are right

public class Program
{
    async static Task Main() => await Task.Run(Background);
    private static void Background() => throw new Exception();
}
Unhandled exception. System.Exception: Exception of type 'System.Exception' was thrown.
   at Program.Background() in C:\Work\test\delegates\Program.cs:line 12
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
   at Program.Main() in C:\Work\test\delegates\Program.cs:line 11
   at Program.<Main>()

Changing the above from

at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)

to

at Task:InvokeContextCallback(Object state)

Doesn't really add much, so should additionally add [DebuggerStepThrough, StackTraceHidden]?

@stephentoub

stephentoub commented Dec 6, 2019 •

Copy link
Copy Markdown
Member

so should additionally add [DebuggerStepThrough, StackTraceHidden]?

Assuming that would still require all of these code contortions that make the code IMO harder to maintain, I'd rather this PR just be closed. If you want to work with the C# team to design/enable propagating attributes from fields lambdas are stored into to the generated methods for those lambdas (or enabling lambdas to be attributed), then we could attribute the fields/lambdas accordingly.

@benaadams benaadams closed this Dec 6, 2019
@stephentoub

Copy link
Copy Markdown
Member

Thanks for understanding.

@benaadams
benaadams deleted the cached-delgates branch February 17, 2020 23:02
@ghost ghost locked as resolved and limited conversation to collaborators Dec 11, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-System.Threading NO-MERGE The PR is not ready for merge yet (see discussion for detailed reasons) tenet-performance-benchmarks Issue from performance benchmark

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants