Monday, March 2, 2009

Blow up a binary with lambdas

Supporting lambda functions require generating additional supporting compiler generated structures. Suppose you wrote helper Each function to iterate over collection
public static void Each(this IEnumerable items, Action action)
foreach (var item in items)
For each call
collection.Each(s => Fu1(s));
Compiler will generate additional delegate and static function stub declaration like below one
args.Each(new CS$<>9__CachedAnonymousMethodDelegate3e8(
b__ff)); [CompilerGenerated] private static void
b__ff(string s) { Fu1(s); } [CompilerGenerated] private static Action CS$<>9__CachedAnonymousMethodDelegate3e8;
In case of ambient local variables capturing compiler will generate helper class. How does this codegeneration impact compiled code size? The simple program below
class Program
static void Fu1(string message) { }
static void Main(string[] args)
// simply iterate over collection using Each helper method
// will be compared to foreach implementation
// foreach(var s in args) { Fu1(s); }

args.Each(s => Fu1(s)); // 1000 lines
will take 140Kb versus 40Kb for similar program which uses foreach construct which means 3X greater size. If we zip binaries the sizes will be 28Kb for lambda vesion versus 2Kb for foreach one. Which means that compressing is good :) Is 3X factor a big one? Don't know. But it explain why my libraries binary code have been growing up rapidly.

No comments:

Post a Comment