controlflow / resharper-heapview

ReSharper Heap Allocations Viewer plugin
MIT License
303 stars 28 forks source link

Empty Delegates: Do They Count? #34

Closed Mike-E-angelo closed 8 years ago

Mike-E-angelo commented 8 years ago

Big big fan of this project. :) I wish it was in R# by default... I basically went down a rabbit hole with my codebase recently... did not know that delegates were so expensive until I got into profiling with dotTrace. Did some investigating and found the JetBrains blog posts that led me to here. Totally bummed about my design decision now but I guess I will carry it with me going forward.

Anyways, the reason for this issue is about empty delegates: () => {}

I've noticed these do not get hints. Are they not counted for some reason? Or possible bug?

Thanks again for your great work!

controlflow commented 8 years ago

The reason you don't get allocation hints is because delegate instance from this "empty" lambda expression will be cached by C# compiler. C# compiler has optimization for simple lambda expressions/anonymous methods/query expression parts - if you don't capture any of variables/this reference from outer scope (like x => x.ToString(), for example, or () => { }), it will emit code that allocates delegate instance once and cache it in static field. So really allocations happens, but you should not worry about it - heapview detects such cases and do not produces allocation hints.

You can observe code generated for such lambda expression by any .NET decompiler.

Mike-E-angelo commented 8 years ago

Awesome... thanks for the insight/explanation, @controlflow!