A few days ago I wanted to use attributes to make my code easier. The problem was that It cost me in performance and I couldn’t afford it at this point of the code, so I decided to use expression to optimize my code.
Lets say we want to make a [DefaultValue] attribute that will set a default value for a property
The Attribute definition:
Now we will use it like that:
Option 1: The simple way to use the attributes is by using reflection:
The code above will work but it is not optimized, of course we can cache the PropertyInfo for each object type to improve performance but it is not good enough.
So I decided to use expression trees to optimize the above code.
Option 2: The idea is to create a static object per type. We can do it by using generic static class this will make sure that each type will compile only once.
Now to use it all we need to do is something is:
After I did that I wanted to make sure that I improved the performance so I tested the reflection why vs the expression way.
I run each solution 10000 times (after caching the PropertyInfo) and the results are (on my laptop)
Reflection: 2900 Milliseconds, Expression trees 30 Milliseconds – about 100 times faster
Here is the test code:
I think that there are many cases that we want to use attributes to make our code easier to read and write and by optimizing it with expression trees we can enjoy a clean code and not paying for it in performance.
BTW: After I did that I created a custom serializer on the same idea (just need to change the Initializer that will return values instead of set the object properties
Keep Writing, Compiling, and Debugging