Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<TDelegate>.Compile and Garbage Collection

When I compile an expression into executable code and get the delegate - does the code get garbage collected when no more references to this delegate exist?

Is there any documentation on this? Because I didn't find anything useful in the MSDN.

like image 292
Alex Shtof Avatar asked Mar 17 '11 14:03

Alex Shtof


1 Answers

Yes, the code can be garbage collected. When you call Compile on an Expression of T, the code is compiled into a DynamicMethod, and those are eligible for garbage collection.

Indeed it's not indicated on the MSDN, but you can have a look at the implementation of Expression<T>.Compile in the DLR, which is what .net 4.0 ships:

http://dlr.codeplex.com/SourceControl/changeset/view/54115#990638

Although the implementation of the compiler was different in .net 3.5, DynamicMethods were still used (source: myself, I implemented System.Linq.Expressions in Mono).

The case where compiled expression trees are not collectible, is when you use Expression<T>CompileToMethod, and that you pass a MethodBuilder from an AssemblyBuilder which was not created with the RunAndCollect flag.

like image 83
Jb Evain Avatar answered Oct 17 '22 21:10

Jb Evain