John Lam 1997 — 2026

Lightweight Code Generation and Python

Recently on the IronPython mailing list, there has been discussion about the new Lightweight Code Generation (LCG) feature in V2.0 of the CLR. This feature is implemented by System.Reflection.Emit.DynamicMethod.

Joel Pobar wrote an entry some time ago (March 21, 2004) that describes how to write “Hello, World” using DynamicMethod. I recall reading this entry and saying to myself: “so what?”. At the time, I didn’t care much about dynamically typed languages that support eval-style programming. So I missed the significance of one bullet point:

Generated methods are able to be reclaimed.

Whoa. This changes everything for dynamically typed languages such as Python on the CLR. It is highly unlikely that future versions of the CLR will support unloading of assemblies from an existing AppDomain. This means that long-running programs that generate code via eval will eventually run out of memory since none of the generated code can be reclaimed by the GC. With LCG, however, dynamically generated methods can be reclaimed by the GC which is a big win for dynamic typing on the CLR.

Jim Hugunin the creator of IronPython and a recent hire at Microsoft wrote the following in a recent post:

LCG is the right way to fix this problem in the near term. Once again, I’ll send you off to one of my co-worker’s blogs for a concrete example: http://blogs.msdn.com/joelpob/archive/2004/03/31/105282.aspx

It should be a trivial matter to support this form of generation as an option in IronPython that is used only on systems that support DynamicMethod. This would mean that 1.1 systems would have an interactive interpreter with a memory leak, but that on 2.0 that same interactive interpreter would stop leaking making it viable in a greater range of circumstances.

Jim’s got an open position for an SDE if you’re interested in working on the future of dynamic typing at Microsoft.