<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Akash Kava &#187; QueryString</title>
	<atom:link href="http://akashkava.com/blog/tag/querystring/feed/" rel="self" type="application/rss+xml" />
	<link>http://akashkava.com/blog</link>
	<description>Founder of NeuroSpeech</description>
	<lastBuildDate>Tue, 10 Apr 2012 18:00:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>C# Optimizations Via Caching &#8211; Part 2</title>
		<link>http://akashkava.com/blog/95/c-optimizations-via-caching-part-2/</link>
		<comments>http://akashkava.com/blog/95/c-optimizations-via-caching-part-2/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:39:14 +0000</pubDate>
		<dc:creator>Akash Kava</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Config]]></category>
		<category><![CDATA[Optimizations]]></category>
		<category><![CDATA[Property]]></category>
		<category><![CDATA[QueryString]]></category>
		<category><![CDATA[Request]]></category>
		<category><![CDATA[Static]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://akashkava.com/blog/?p=95</guid>
		<description><![CDATA[I decided to write part 2 of optimization, with C# Project, to actually test the performance for accessing NameValueCollection and Property access. I had lot of comments by extra smart people quoting regarding my previous post at &#34;C# Optimizations Via Caching&#34; . That all methods posted do not do any significant impact on performance, I [...]]]></description>
			<content:encoded><![CDATA[<div style="float: right; width: 42px; padding-right: 10px; margin: 0 0 0 10px;">
		<script type="text/javascript">
		<!--
		digg_url = "http://akashkava.com/blog/95/c-optimizations-via-caching-part-2/";
		digg_bgcolor = "";
		digg_skin = "";
		digg_window = "";
		digg_title = "C%23+Optimizations+Via+Caching+%26%238211%3B+Part+2";
		digg_media = "";
		digg_topic = "";
		digg_bodytext = "";
		//-->
		</script>
		<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></div><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fakashkava.com%2Fblog%2F95%2Fc-optimizations-via-caching-part-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fakashkava.com%2Fblog%2F95%2Fc-optimizations-via-caching-part-2%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I decided to write part 2 of optimization, with C# Project, to actually test the performance for accessing NameValueCollection and Property access.</p>
<p>I had lot of comments by extra smart people quoting regarding my previous post at <a href="http://akashkava.com/blog/?p=18" target="_blank">&quot;C# Optimizations Via Caching&quot;</a> . That all methods posted do not do any significant impact on performance, I wonder people just have habit of posting any thing without even thinking once.</p>
<p>So I decided to write a piece of code to actually demonstrate the optimization impact with statistics. In this Visual Studio 2008 C# Console Project, I wrote a simple code to access an application config value directly for 10,000 times in a loop and then to access it via statically cached variable. And in second part, I implemented accessing property and accessing a local variable nearly 10 million times to detect noticeable effect.</p>
<p>The tests are as follow,</p>
<p>Lets look at the test code to access config values, also please note that config values are stored in NameValueCollection, which is same object used in Request, Response and Session objects in web request.</p>
<blockquote><pre class="csharpcode"><span class="rem">// Configuration Access Test</span>
Console.WriteLine(<span class="str">&quot;Testing Direct Config Access&quot;</span>);

Test(1000000, () =&gt; {
     <span class="kwrd">string</span> v = System.Configuration.ConfigurationManager.AppSettings[<span class="str">&quot;Key&quot;</span>];
});

Console.WriteLine(<span class="str">&quot;Testing Cached Access&quot;</span>);
Test(1000000, () =&gt; {
     <span class="kwrd">string</span> v = SettingVal;
});</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
</blockquote>
<p>Following is the result, on Intel Centrino Duo with 1GB of RAM, this shows that the code with cached access in static variable is 100 times faster.</p>
<blockquote>
<p>Testing Direct Config Access<br />
    <br />Time Difference 1125 MilSecs</p>
<p>Testing Cached Access<br />
    <br />Time Difference 15.625 MilSecs</p>
</blockquote>
<p>So now next time you code, remember it to not access frequently in loops.</p>
<p>Lets talk about property access,</p>
<blockquote>
<pre class="csharpcode"><span class="rem">// Property in Loop Test</span>
<span class="kwrd">int</span> pc = 10000000;
Console.WriteLine(<span class="str">&quot;Testing Direct Property Access&quot;</span>);
Test(() =&gt; {
    Person p1 = <span class="kwrd">new</span> Person();
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; pc; i++)
    {
        <span class="kwrd">string</span> v = p1.Name;
    }
});

Console.WriteLine(<span class="str">&quot;Testing Local Variable Access&quot;</span>);
Test(() =&gt; {
    Person p1 = <span class="kwrd">new</span> Person();
    <span class="kwrd">string</span> t = p1.Name;
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; pc; i++)
    {
        <span class="kwrd">string</span> v = t;
    }
});</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
</blockquote>
<p>In order to detect any noticeable difference, we have to loop for about 10 million times, however, in any usual code, you will be accessing 100s of properties, so it may make a good difference when you write code, which executes million times parallel.</p>
<blockquote>
<p>Testing Direct Property Access<br />
    <br />Time Difference 140.625 MilSecs</p>
<p>Testing Local Variable Access<br />
    <br />Time Difference 46.875 MilSecs</p>
</blockquote>
<p>Now based on the amount of free memory, and cpu speed, you might have to configure the number of iterations up and down to get a good noticeable effect of two different ways.</p>
<p>I can clearly see the difference, remember on normal piece of code, you will be accessing over 10 to 100s of properties again and again.</p>
<p>Click on <a href="http://akashkava.com/blog/wp-content/uploads/2009/03/cachingstats.zip">Caching Stats Visual Studio Project</a> to download and test by yourself.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fakashkava.com%2Fblog%2F95%2Fc-optimizations-via-caching-part-2%2F&amp;title=C%23%20Optimizations%20Via%20Caching%20%26%238211%3B%20Part%202"><img src="http://akashkava.com/blog/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://akashkava.com/blog/95/c-optimizations-via-caching-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C# Optimizations Via Caching</title>
		<link>http://akashkava.com/blog/18/c-optimizations-via-caching/</link>
		<comments>http://akashkava.com/blog/18/c-optimizations-via-caching/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 13:59:58 +0000</pubDate>
		<dc:creator>Akash Kava</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Config]]></category>
		<category><![CDATA[Optimizations]]></category>
		<category><![CDATA[Property]]></category>
		<category><![CDATA[QueryString]]></category>
		<category><![CDATA[Request]]></category>
		<category><![CDATA[Static]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://akashkava.com/blog/?p=18</guid>
		<description><![CDATA[Being computer science expert, I can visualize the load on Processor when I write the code, and though its cumbersome sometime to write more code to perform optimized operation,but its real worth while to spend time to understand Caching in programming. Static Caching Config Values The configuration values that you probably store in some config [...]]]></description>
			<content:encoded><![CDATA[<div style="float: right; width: 42px; padding-right: 10px; margin: 0 0 0 10px;">
		<script type="text/javascript">
		<!--
		digg_url = "http://akashkava.com/blog/18/c-optimizations-via-caching/";
		digg_bgcolor = "";
		digg_skin = "";
		digg_window = "";
		digg_title = "C%23+Optimizations+Via+Caching";
		digg_media = "";
		digg_topic = "";
		digg_bodytext = "";
		//-->
		</script>
		<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></div><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fakashkava.com%2Fblog%2F18%2Fc-optimizations-via-caching%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fakashkava.com%2Fblog%2F18%2Fc-optimizations-via-caching%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Being computer science expert, I can visualize the load on Processor when I write the code, and though its cumbersome sometime to write more code to perform optimized operation,but its real worth while to spend time to understand Caching in programming.</p>
<h1>Static Caching Config Values</h1>
<p>The configuration values that you probably store in some config file, or some xml, or some registry etc should be statically cached in any class. For example, you need to access &quot;AppConnectionString&quot; defined in web.config or app.config, if you use expression</p>
<blockquote><pre class="csharpcode">WebConfigurationManager.ConnectionStrings[<span class="str">&quot;AppConnectionString&quot;</span>]</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>every time then it would be very costly as first it tries to get instance of config file, then the section and then once again the HashTable of probably NamedValueCollection type and so on. This all is very costly for any value that is stored in config file and which stays unchanged for months or even years. I would always access it in a static class like this.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">string</span> _AppConnectionString = <span class="kwrd">null</span>;
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> AppConnectionString
{
    <span class="kwrd">if</span>(_AppConnectionString == <span class="kwrd">null</span>)
    {
        _AppConnectionString =
            WebConfigurationManager
             .ConnectionStrings[<span class="str">&quot;AppConnectionString&quot;</span>]
             .ConnectionString;
    }
    <span class="kwrd">return</span> _AppConnectionString;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<h1>Property Cache in Local Variable</h1>
<p>Consider following code</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">void</span> DrawEffectRectangle(Rectangle r)
{
   <span class="kwrd">for</span>(<span class="kwrd">int</span> i=50; i&gt;=0;i--)
   {
      SetColor(i*5);
      Draw3dRect(r.Left - i, r.Top - i, r.Right + i, r.Bottom + i);
   }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>This method uses 4 properties, Left, Top, Right and Bottom, now consider following effective code which produces exactly same effect.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">void</span> DrawEffectRectangle(Rectangle r)
{
   <span class="kwrd">int</span> left = r.Left;
   <span class="kwrd">int</span> top = r.Top;
   <span class="kwrd">int</span> bottom = r.Bottom;
   <span class="kwrd">int</span> right = r.Right;
   <span class="kwrd">for</span>(<span class="kwrd">int</span> i=50; i&gt;=0;i--)
   {
      SetColor(i*5);
      Draw3dRect(left - i, top - i, right + i, bottom + i);
   }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Now note, the calls to property evaluation has been reduced, lets assume one property access code takes 1ms then this code will execute 446ms times faster then the earlier code.</p>
<p><strong>Note, you should use this technique carefully after examining that the value of these property evaluations are constant throughout the execution.</strong></p>
<h1>Cache Before Loop</h1>
<p>Assuming following code,</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">for</span>(<span class="kwrd">int</span> i=0;i&lt;Results.Length;i++)
{
   ProcessResult(Results[i]);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Now here as well, expression i&lt;Results.Length gets evaluated Results.Length times, assuming it to be an array. But consider the following code,</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">int</span> len = Results.Length;
<span class="kwrd">for</span>(<span class="kwrd">int</span> i=0;i&lt;len;i++)
{
   ProcessResult(Results[i]);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Caching once again the Length in a local variable reduces Property Evaluation code.</p>
<h1>QueryString Caching</h1>
<p>Most of the time, we have habbit of using &#8216;Request.QueryString[&quot;SomeID&quot;]&#8216; this is very bad if you keep on calling this way, you must cache this in beginning of Page processing that will significantly improve your Web Server Performance. I would use following way to initialize my QueryString based Page variables.</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">private</span> T GetQueryStringValue&lt;T&gt;(<span class="kwrd">string</span> name, T def)
{
   <span class="kwrd">object</span> val = Request.QueryString[name];
   <span class="kwrd">if</span>(val == <span class="kwrd">null</span>)
      <span class="kwrd">return</span> def;
   <span class="kwrd">return</span> (T)Converter.ChangeType(<span class="kwrd">typeof</span>(T),val);
}

<span class="kwrd">private</span> <span class="kwrd">long</span> CustomerID = 0;
<span class="kwrd">private</span> <span class="kwrd">string</span> Process = <span class="str">&quot;&quot;</span>;

<span class="kwrd">private</span> <span class="kwrd">void</span> Page_Load(<span class="kwrd">object</span> sender, EventArgs e)
{
   CustomerID = GetQueryStringValue&lt;<span class="kwrd">long</span>&gt;(<span class="str">&quot;CustomerID&quot;</span>, 0);
   Process = GetQueryStringValue&lt;<span class="kwrd">string</span>&gt;(<span class="str">&quot;Process&quot;</span>, <span class="str">&quot;Signup&quot;</span>);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>And then using the values of CustomerID and Process variables rather then accessing Request.QueryString object again and again. There are two advantages in it, first, you can avoid Request.QueryString calls, and second you can compare native type comparisons to evaluate your algorithm flow. And you can see yourself after decompiling Request object through Reflector, that each access of Request.QueryString and its indexer basically requires more then 20-80 steps to get final result. Sure processor has 3 GHz but that doesnt mean that 1000 requests can just waste so many cpu cycles and finally frustrating the end user who is waiting expecting some result !!</p>
<h1>Session Variable Caching</h1>
<p>I would also try to cache, session variable in local page class as defined following,</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">long</span> _SessionWebUserID = -1;
<span class="kwrd">private</span> <span class="kwrd">long</span> SessionWebUserID{
   get{
      <span class="kwrd">if</span>(_SessionWebUserID == -1)
      {
         _SessionWebUserID = 0;
         <span class="kwrd">object</span> val = Session[<span class="str">&quot;WebUserID&quot;</span>];
         <span class="kwrd">if</span>(val != <span class="kwrd">null</span>)
         {
            _SessionWebUserID = (<span class="kwrd">long</span>)val;
         }
      }
      <span class="kwrd">return</span> _SessionWebUserID;
   }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Sure this method has additional _SessionWebUserID != -1 comparison everytime you access the property, but belive me, its far less costly then accessing Session NamedValueCollection again and again.</p>
<p>However the drawback is, if you cache session variable for longer period then its life in static variable, if it changes outside in session, you will never know. Thats why I always keep it as instance property instead of static, so I assume that atleast for this instance of page, the session value is constant.</p>
<h1>Avoid Property of Property Style</h1>
<p>Consider following code,</p>
<blockquote>
<pre class="csharpcode"><span class="kwrd">string</span> url = HttpContext.Current.Request.Url;
<span class="kwrd">string</span> method = HttpContext.Current.Request.Method;</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Both method has HttpContext.Current.Request as common code, and it actually has 2 Property Evaluation codes. Considering simple property evaluation execution time is 1ms, above code finishes in 6ms.</p>
<p>Ideally such code should be written as,</p>
<blockquote>
<pre class="csharpcode">HttpRequest request = HttpContext.Current.Request;
<span class="kwrd">string</span> url = request.Url;
<span class="kwrd">string</span> method = request.Method;</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</blockquote>
<p>Now this rewritten code finishes in 4ms, as first statement executes two property evaluation code to get final useful HttpRequest object.</p>
<h1>Caching Method Results</h1>
<p>Sure all of above methods even apply to method results too, as Property evaluation is just an internal get_Property method.</p>
<h1>Result</h1>
<p>Ok fine, I do the caching but how it improves performance? The answer is quite simple, each of above discussed methods requires numerous Property evaluation, Hashtable eveluation code, in order to read certain values. Now accessing local stack variable or static variable is many times faster then accessing property as it is a new method to access some other variable or some calculated variable. The indexed or hashed properties take even more time as the search is dependent upon the number of items present in the list or dictionary. Each such operation may execute few millsecond faster then before, but the overall performance increases with many concurrent execution. Not only CPU cycles but memory usage also can be improved as less method calls, less stack in use and less overhead on memory.</p>
<p>Oh such big lecture just for avoiding Property Evaluations? Well yes, remember Property Evaluation code is nothing but a simple method execution for CPU. And inside the .NET CLR environment, CPU needs to do a lot before an actual code is executed. <strong>Please note, this is assumed hypothetical Call sequence, the actual .NET CLR call sequence can be much more complex.</strong></p>
<ol>
<li>Access target object (in which property exists) </li>
<li>Access internal &quot;Get&quot; method handle for this target object&#8217;s type </li>
<li>Allocate the Stack </li>
<li>Do some book keeping, note the pointer values for tracking Exception StackTrace </li>
<li>Setup local variables if any </li>
<li>Move to the pointer of first instruction </li>
<li>Evaluate expressions and actual code (for NamedValueCollection this could be quite long) </li>
<li>Push result on stack </li>
<li>Finish the Call </li>
<li>Pop the result </li>
<li>Unwind stack and do some book keeping to unwind Exception StackTrace </li>
</ol>
<p>So, you can see, CPU needs to do a lot just before it can give you property evaluation result. And in case of Cached value in local variable, this can simply reduce in one or two instructions for subsequent frequent access.</p>
<h1>Memory Usage</h1>
<p>Using more such cached variables doesnt increase memory overhead? Well significantly not, because you are not going to have million such variables in one single threaded execution, most of these variables will be reused from time to time. Each local cached variable in method execution is on stack, and it only takes one space unit, however executing actual property again and again will even require more stack usage.</p>
<h1>This isn&#8217;t same as External Caching</h1>
<p>Sure web servers are written with great deal of effort and do provide good caching mechanism. Even ASP.NET has various caching methods, but those caching things are for very generalized purpose, the methods I am detecting here is not supposed to be misunderstood with the page, control caching. Because even other caching methods requires at least first time complete processing in order to get the results. Also these are pure processor level execution improvements, it has nothing to do with where your application is executing, it can be your web server code or your mobile app code or even database assembly code.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fakashkava.com%2Fblog%2F18%2Fc-optimizations-via-caching%2F&amp;title=C%23%20Optimizations%20Via%20Caching"><img src="http://akashkava.com/blog/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://akashkava.com/blog/18/c-optimizations-via-caching/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

