The cost of creating Expression Trees

First, merry xmas etc. etc..

Second – expression trees. I just wanted to post a short blog about the actual cost of creating trees that can be illustrated by comparing the following two code samples: –



See the difference? Rather than creating the expression inline of the for loop (Sample A), we create it once outside the for loop and reuse it for all iterations (Sample B). (FYI: ParseExpression() does absolutely nothing – it’s just there as a means to an end). Here’s the timing results for 1,000,000 loops: –


Running the performance tuning wizard against this shows us some cheeky reflection calls behind-the-scenes which even brings up a performance warning: –



The lesson to be learned? Expression Trees are an extremely useful tool in your arsenal – and can be used to give big performance gains over e.g. reflection or even dynamic, but ensure that you cache the expressions themselves otherwise the cost of creating the tree can outweigh the benefits gained from them.

2 thoughts on “The cost of creating Expression Trees

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s