Search code examples
c#.netmemory-leaksexpressionexpression-trees

Do compiled expression trees leak?


In my understanding, JIT-ed code never gets released from memory while the program is running. Does this mean that repeatedly calling .Compile() on expression trees leaks memory?

The implication of that would be to only compile expression trees in static constructors or cache them in some other way, which may not be as simple. Right?


Solution

  • They are probably GCed... LambdaExpression.Compile() uses the LambdaCompiler.Compile(LambdaExpression, DebugInfoGenerator) class, that through one of the LambdaCompiler constructors uses DynamicMethod that, from MSDN:

    Defines and represents a dynamic method that can be compiled, executed, and discarded. Discarded methods are available for garbage collection.