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
Test | Duration [ms] |
---|---|
Regualar property | 31 |
Reflection | 1026 |
Reflection with cached PropertyInfo | 510 |
Compiled Expression | 286.879 |
Cached compiled Expression | 58 |
Delegate | 299.173 |
Cached delegate | 3008 |
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.