{"id":1066,"date":"2010-10-11T08:42:09","date_gmt":"2010-10-11T07:42:09","guid":{"rendered":"http:\/\/www.minddriven.de\/?p=1066"},"modified":"2010-10-11T08:42:09","modified_gmt":"2010-10-11T07:42:09","slug":"efficient-expression-values","status":"publish","type":"post","link":"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/c-sharp\/efficient-expression-values","title":{"rendered":"C#: Efficient retrieval of Expression values"},"content":{"rendered":"<p>Some days ago I&#8217;ve had an interesting technical discussion with a colleague of mine regarding the possibility of implementing <strong>Guard classes with Expressions in C#<\/strong>. Such a class enables easy argument checking in form of <em>(technical) preconditions<\/em> on method entry. Thereby the checking logic is encapsulated in the <a href=\"http:\/\/ajdotnet.wordpress.com\/2009\/08\/01\/posting-guards-guard-classes-explained\/\">Guard class<\/a>.<\/p>\n<p>One method of such a <code>Guard<\/code> class could be <code>AssertNotNull()<\/code> which checks, if a given method argument equals <code>null<\/code> and if true throws an <code>ArgumentNullException<\/code>. By the use of Expressions the parameter to check can be given to <code>AssertNotNull()<\/code> in a very elegant way:<\/p>\n<pre class=\"brush:csharp;\">public void MyMethod(SomeType elem)\r\n{\r\n    Guard.AssertNotNull(() =&gt; elem);\r\n\r\n    \/\/ actual method logic\r\n}<\/pre>\n<p>Through evaluation of the <code>Expression<\/code> the <code>AssertNotNull()<\/code> method is able to extract both the <strong>name and value of the argument<\/strong>. Thus there&#8217;s no necessity to provide both as parameters to <code>AssertNotNull()<\/code>. Moreover you do not need to provide the argument name as <code>string<\/code>.<\/p>\n<h3>Value by compilation<\/h3>\n<p>It&#8217;s very easy to extract the argument value through <strong>compilation and invocation<\/strong> of the <code>Expression<\/code>. Hence this solution is often taken by developers who work with Expressions in this way. The following snippet shows this implementation:<\/p>\n<pre class=\"brush:csharp;\">public static class Guard\r\n{\r\n    public static void AssertNotNull&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; selector)\r\n    {\r\n        T value = selector.Compile().Invoke();\r\n        if (value == null)\r\n        {\r\n            string name = ((MemberExpression)selector.Body).Member.Name;\r\n            throw new ArgumentNullException(name);\r\n        }\r\n    }\r\n}<\/pre>\n<h3>Value by evaluation<\/h3>\n<p>In the conversation with my colleague we caught the point that the extraction of the argument value from an <code>Expression<\/code> is even possible <strong>without performing the costly compilation<\/strong>. This is enabled by converting the <code>Expression<\/code> into a <code>ConstantExpression<\/code>, from which we can catch the value by executing <code>GetValue()<\/code> on a <code>FieldInfo<\/code> instance:<\/p>\n<pre class=\"brush:csharp;\">public static class Guard\r\n{\r\n    public static void AssertNotNull&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; selector)\r\n    {\r\n        var memberSelector = (MemberExpression)selector.Body;\r\n        var constantSelector = (ConstantExpression)memberSelector.Expression;\r\n        object value = ((FieldInfo)memberSelector.Member)\r\n            .GetValue(constantSelector.Value);\r\n\r\n        if (value == null)\r\n        {\r\n            string name = ((MemberExpression)selector.Body).Member.Name;\r\n            throw new ArgumentNullException(name);\r\n        }\r\n    }\r\n}<\/pre>\n<p>This doesn&#8217;t look very spectacular on first sight. The code is more complicated and it&#8217;s necessary to provide a variable in the <code>Expression<\/code>. Properties and data hierarchies don&#8217;t work with this solution, but this shouldn&#8217;t be a problem when checking argument values against <code>null<\/code>. Of course with a more sophisticated solution (iterative\/recursive evaluation of the <code>Expression<\/code> tree) you can enable such scenarios, but this is out of scope of this blog post&#8230;<\/p>\n<h3>Looking at the execution times<\/h3>\n<p>So what&#8217;s the point of the second solution? It&#8217;s simple: compilation is <strong>much more time-intensive<\/strong>! In a little runtime test I&#8217;ve compared both solutions. A call of <code>AssertNotNull()<\/code> with a valid argument (<code>!= null<\/code>) over 10.000 iterations resulted in the following execution times:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1071\" title=\"Execution times for Expression evaluation\" src=\"http:\/\/www.minddriven.de\/wp-content\/uploads\/2010\/10\/ExpressionEvaluation.png\" alt=\"\" width=\"249\" height=\"60\" \/><\/p>\n<p>Please note the immensive time difference! The compiled solution takes more than <strong>53 seconds<\/strong>, while the evaluation takes less than <strong>0,35 seconds<\/strong>. This makes a <strong>time factor of more than 156<\/strong>, by which the evaluated solution is faster than the compiled approach.<\/p>\n<h3>Conclusion<\/h3>\n<p>When handling with Expressions you should take the execution time into account! Once a method is executed inside of a loop and you follow defensive programming and check method parameters at every place, an argument check can become an important time factor. When possible you should <strong>favor evaluation over compilation<\/strong> of Expressions.<\/p>\n<p><a href=\"http:\/\/www.dotnetkicks.com\/kick\/?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1066\"><img decoding=\"async\" src=\"http:\/\/www.dotnetkicks.com\/Services\/Images\/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.minddriven.de%2f%3fp%3d1066\" border=\"0\" alt=\"kick it on DotNetKicks.com\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Some days ago I&#8217;ve had an interesting technical discussion with a colleague of mine regarding the possibility of implementing Guard classes with Expressions in C#. Such a class enables easy argument checking in form of (technical) preconditions on method entry. Thereby the checking logic is encapsulated in the Guard class. One method of such a &hellip; <a href=\"https:\/\/www.minddriven.de\/index.php\/technology\/dot-net\/c-sharp\/efficient-expression-values\" class=\"more-link\"><span class=\"screen-reader-text\">C#: Efficient retrieval of Expression values<\/span> weiterlesen<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[310,279,177,281,280],"class_list":["post-1066","post","type-post","status-publish","format-standard","hentry","category-c-sharp","tag-c-sharp","tag-compile","tag-expressions","tag-getvalue","tag-invoke"],"_links":{"self":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/1066","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/comments?post=1066"}],"version-history":[{"count":8,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/1066\/revisions"}],"predecessor-version":[{"id":1076,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/posts\/1066\/revisions\/1076"}],"wp:attachment":[{"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/media?parent=1066"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/categories?post=1066"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.minddriven.de\/index.php\/wp-json\/wp\/v2\/tags?post=1066"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}