Daniel Palme

Daniel Palme

.NET consultant from Germany.

Blog > Reflection vs. compiled expressions vs. delegates - Performance comparision

Reflection vs. compiled expressions vs. delegates - Performance comparision

I'm currently working on an application which uses reflection to create a generic UI. Therefore I was interested in the performance impact of reflection. In this post I will do a comparison between the various possibilities to access a property.

The test setup

The following methods are used to access a property called Name in a class Person:

Access the property directly:

string name = p.Name;

Use reflection:

var property = p.GetType().GetProperty("Name");
string name = (string)property.GetValue(p, null);

This test is executed twice. First the PropertyInfo is created in every iteration. In the second test one instance is reused.

Use compiled expression:

ParameterExpression arg = Expression.Parameter(p.GetType(), "x");
Expression expr = Expression.Property(arg, "Name");

var propertyResolver = Expression.Lambda<Func<Person, object>>(expr, arg).Compile();

string name = (string)propertyResolver(p);

This test is also executed twice. First the Expression is created in every iteration. In the second test one instance is reused.

Use delegates:

ParameterExpression arg = Expression.Parameter(p.GetType(), "x");
Expression expr = Expression.Property(arg, "Name");

var propertyResolver = Expression.Lambda(expr, arg).Compile();

string name = (string)propertyResolver(p);

This seems to be the same as the test with the compiled expression. But there is a subtle change: The lambda is created without type information.

Each test is executed 1.000.000 times and the overall time is measured.

The results

Overview

TestDuration [ms]
Regualar property31
Reflection1026
Reflection with cached PropertyInfo510
Compiled Expression286.879
Cached compiled Expression58
Delegate299.173
Cached delegate3008

Conclusion

Using the property is of course the fasted way to get the value of a (known) property. But also reflection is not that slow, especially when you reuse the PropertyInfo object.
Compiling an expression is a time consuming operation, but if you reuse the compiled expression the performance is equal to the regular property access. Compilation of expressions only makes sense, if you have to process a lot of objects.
Delegates are relatively slow, because type information is missing compared to compiled expressions.

Downloads

ReflectionPerformance.7z

Tags: .NET, C#
 

Related posts

 

New comment

:

:

:

:

 

Comments

#1
Miguel Angelo

Miguel Angelo

05/23/2013

The cached delegate time of 3008ms makes no sense... it should be faster than the no-cache version of itself, that took 299.173ms... shouldn't it?
 
#2
Daniel

Daniel

05/24/2013

@Miguel:
It is faster. I think you are misinterpreting the numbers. The '.' is not used as a decimal separator but as a grouping symbol.