Advertisement
Guest User

Expression caching

a guest
Nov 6th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. class Program
  2.     {
  3.         private static readonly IDictionary<int, Object> _cache = new Dictionary<int, Object>();
  4.  
  5.         public static void SomeToStringCalls()
  6.         {
  7.             Console.WriteLine(ToString(i => (i + 1).ToString(), 1));
  8.             Console.WriteLine(ToString(i => (i + 1).ToString(), 2));
  9.             Console.WriteLine(ToString(i => (i + 2).ToString(), 3));
  10.             Console.WriteLine(ToString(i => (i + 2).ToString(), 4));
  11.         }
  12.  
  13.         private static int GetExpressionHash<T>(Expression<Func<T, string>> expression)
  14.         {
  15.             int hash = expression.Body.ToString().GetHashCode();
  16.             expression.Parameters.ToList().ForEach(param => hash = hash * 31 + param.Name.GetHashCode());
  17.             return hash;
  18.         }
  19.  
  20.         private static string ToString<T>(Expression<Func<T, string>> expression, T input)
  21.         {
  22.             var cacheKey = GetExpressionHash(expression);
  23.             if (!_cache.ContainsKey(cacheKey))
  24.             {
  25.                 _cache[cacheKey] = expression.Compile();
  26.                 Console.WriteLine(String.Format("Compiling expression {0}", expression.ToString()));
  27.             }
  28.             var method = (Func<T, string>) _cache[cacheKey];
  29.             return method.Invoke(input);
  30.         }
  31.  
  32.         static void Main(string[] args)
  33.         {
  34.             SomeToStringCalls();
  35.             Console.ReadLine();
  36.         }
  37.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement