title: Caching compiled lambda expressions
body: <p>I need to get some info passed as a lambda expression to some methods. Basically, it's a way to add information to a database query. A simple example would be:</p>
  
  <pre><code>companyData.GetAll(
     where =&gt; "SomeField = @SOMEFIELD",
     order =&gt; "Id",
     SOMEFIELD =&gt; new Parameter {DbType = DbType.String, Value = "some value"}
  )
  </code></pre>
  
  <p>It's working pretty well, except for the fact that I need to call <a href="http://msdn.microsoft.com/en-us/library/bb356928.aspx" rel="noreferrer">LambdaExpression.Compile</a> to get the parameter object, which have a big perfomance impact.</p>
  
  <p>To get faster results, I've come with this naive caching test:</p>
  
  <pre><code>class ExpressionCache&lt;T,U&gt;
  {
  
      private static ExpressionCache&lt;T, U&gt; instance;
      public static ExpressionCache&lt;T, U&gt; Instance
      {
          get
          {
              if (instance == null) {
                  instance = new ExpressionCache&lt;T, U&gt;();
              }
              return instance;
          }
      }
  
      private ExpressionCache() { }
  
      private Dictionary&lt;string, Func&lt;T, U&gt;&gt; cache = new Dictionary&lt;string, Func&lt;T, U&gt;&gt;();
  
      public Func&lt;T, U&gt; Get(Expression&lt;Func&lt;T, U&gt;&gt; expression)
      {
          string key = expression.Body.ToString();
          Func&lt;T,U&gt; func;
          if (cache.TryGetValue(key, out func)) {
              return func;
          }
          func = expression.Compile();
          cache.Add(key, func);
          return func;
      }
  }
  </code></pre>
  
  <p>This class made a huge difference: from about 35000 milliseconds on 10000 iterations to about 700.</p>
  
  <p>Now comes the question: what kind of problem I will run into using the expression body as the key for the dictionary? </p>