<?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>Chillout Lounge &#187; C#</title>
	<atom:link href="http://logukrishnan.net/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://logukrishnan.net</link>
	<description>Thoughts...Perceptions...Opinions...</description>
	<lastBuildDate>Sun, 25 Jul 2010 20:46:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>PERFORMANCE Code Killer – Unaligned Memory &#8211; C# Structs</title>
		<link>http://logukrishnan.net/2009/02/24/performance-code-killer-%e2%80%93-unaligned-memory-c-structs/</link>
		<comments>http://logukrishnan.net/2009/02/24/performance-code-killer-%e2%80%93-unaligned-memory-c-structs/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 10:41:41 +0000</pubDate>
		<dc:creator>Logu Krishnan</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://logukrishnan.net/?p=64</guid>
		<description><![CDATA[Recently I was analyzing a .NET Application for performance which had lots of structs defined in it, and happened to hit a strange reality. Unaligned Memory problem! I was running a profiler, and found that the memory allocated for few structs are huge than it should normally allocate (based on my own math of counting [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-family: Segoe UI;color: black;font-size: 10pt">Recently I was analyzing a .NET Application for performance which had lots of structs defined in it, and happened to hit a strange reality. </span><span style="font-family: Segoe UI;color: black;font-size: 10pt">Unaligned Memory problem!<br />
</span><span style="font-family: Segoe UI;color: black;font-size: 10pt">I was running a profiler, and found that the memory allocated for few structs are huge than it should normally allocate (based on my own math of counting the bytes). When I probed further, there was an interesting discovery. Read on… </span></p>
<p><span style="color: black"><span style="font-family: Segoe UI;font-size: 9pt"><strong>Alright here is a little head spinner… What is the difference between the following structures?</strong><br />
</span><span style="font-family: Courier New;font-size: 10pt"><br />
struct BadStructure<br />
{<br />
char c1;<br />
int i;<br />
char c2;<br />
}</span><span style="font-family: Tahoma;font-size: 8pt"><br />
</span><span style="font-family: Segoe UI;font-size: 10pt"><strong>Nothing much, except the jumbled type declarations… Huh?<br />
</strong><br />
Fine, Now let&#8217;s look at the size of these structures,</span></span></p>
<p>struct GoodStructure<br />
{<br />
int i;<br />
char c1;<br />
char c2;<br />
}</p>
<p>The size of <span style="text-decoration: underline">BadStructure</span> Structure in:<br />
.NET Framework <strong>3.5</strong> : Managed sizeof= <strong>12 Bytes</strong>, Marshal.Sizeof = <strong>12 Bytes</strong></p>
<p>The size of <span style="text-decoration: underline">GoodStructure</span> Structure in:<br />
.NET Framework <strong>3.5</strong> : Managed sizeof= <strong>8 Bytes</strong>, Marshal.Sizeof = <strong>8 Bytes</strong></p>
<p>[Note: Size of int=4, char=2]</p>
<p>The Reason behind these differences is &#8220;BYTE ALIGNMENT&#8221;, As with the default packing in unmanaged C++, integers are laid out on four-byte boundaries, so while the first<br />
character uses two bytes (a char in managed code is a Unicode character, thus occupying two bytes), the integer moves up to the next 4-byte boundary, and the second character uses the subsequent 2 bytes. The resulting structure is 12 bytes when measured with Marshal.SizeOf.</p>
<p>32 bit microprocessors typically organize memory as shown below.</p>
<p><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
        Byte0  Byte1  Byte2 Byte3 </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
0&#215;1000 </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
0x1004   A0     A1     A2     A3 </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
0&#215;1008 </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
0x100C          B0     B1     B2 </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
0x1010  B3 </span></p>
<p><span style="color: black"><span style="font-family: Segoe UI;font-size: 10pt">Most of the processer architectures cannot read data from odd addresses.<br />
Processor Architectures are inefficient in reading the data if it starts at an address not divisible by four.<br />
Memory is accessed by performing 32 bit bus cycles. 32 bit bus cycles can however be performed at addresses that are divisible by 4. So for efficiency purposes, compilers add the so-called pad bytes. The reasons for not permitting misaligned long word reads and writes are not difficult to see. For example, an aligned long word A would be written as A0, A1, A2 and A3.</span></span><span style="color: black;font-size: 8pt"><span style="font-family: Tahoma"><br />
</span><span style="font-family: Segoe UI">Here is the IL. </span></span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
.class nested private sequential ansi sealed beforefieldinit BadValueType </span><span style="font-family: Courier New;color: #555555;font-size: 10pt"><br />
extends [mscorlib]System.ValueType<br />
{<br />
.field public char c1<br />
.field public char c2<br />
.field public int32 i<br />
</span><span style="font-family: Courier New;color: #555555;font-size: 10pt">} </span><span style="color: black;font-size: 8pt"><span style="font-family: Tahoma"><br />
<strong>In the .NET Framework 3.5, the JIT does enforce a Sequential layout (if specified) for the managed layout of value types</strong>,<br />
</span><span style="font-family: Verdana">We can use the <strong>System.Runtime.InteropServices</strong> namespace and the <strong>StructLayoutAttribute</strong> class to control the physical layout of the data fields in the Microsoft .NET Framework 3.5<br />
</span></span></p>
<p>Thus the microprocessor can read the complete long word in a single bus cycle. If the same microprocessor now attempts to access a long word at address 0x100D, it will have to read bytes B0, B1, B2 and B3. Notice that this read cannot be performed in a single 32 bit bus cycle. The microprocessor will have to issue two different reads at address 0x100C and 0&#215;1010 to read the complete long word. Thus it takes twice the time to read a misaligned long word.</p>
<p>The following byte padding rules will generally work with most 32 bit processor.<br />
a. single byte numbers can be aligned at any address<br />
b. Two byte numbers should be aligned to a two byte boundary<br />
c. Four byte numbers should be aligned to a four byte boundary</p>
<p>This is the cause of the difference.<br />
<strong>Fine…. How do we fix this ?</strong></p>
<p>the .NET compilers all apply a StructLayoutAttribute to structures, specifying a Sequential layout. This means that the fields are laid out in the type according to their order in the source file.<br />
Fix = specify StructLayout [LayoutKind Sequential,Pack = 1] for the struct.</p>
<p><span style="color: black"><span style="font-family: Segoe UI;font-size: 10pt">Watchout for structures when you create them next time, and think about playing around with &#8216;m&#8217; structures with &#8216;n&#8217; size…. m x n = !!!</span></span></p>
]]></content:encoded>
			<wfw:commentRss>http://logukrishnan.net/2009/02/24/performance-code-killer-%e2%80%93-unaligned-memory-c-structs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Session on WPF for Chennai .NET UG</title>
		<link>http://logukrishnan.net/2007/07/16/session-on-wpf-for-chennai-net-ug/</link>
		<comments>http://logukrishnan.net/2007/07/16/session-on-wpf-for-chennai-net-ug/#comments</comments>
		<pubDate>Mon, 16 Jul 2007 10:39:40 +0000</pubDate>
		<dc:creator>Logu Krishnan</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Chennai User Group]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://logukrishnan.net/?p=62</guid>
		<description><![CDATA[I&#8217;m planning to do a new session on Windows Presentation Foundation [WPF] this weekend. If you are interested register @ http://groups.msn.com/chennainetusergroup/july21stsessionregistration.msnw   Madhu [Solutions Architect from Polaris Labs] is doing session on Windows Communication Foundation [WCF] on the same day.]]></description>
			<content:encoded><![CDATA[<p style="margin: 0in;font-family: 'Trebuchet MS';font-size: 10pt">I&#8217;m planning to do a new session on Windows Presentation Foundation [WPF] this weekend.</p>
<p style="margin: 0in"><span style="font-family: 'Trebuchet MS';font-size: 10pt">If you are interested register @ </span><a href="http://groups.msn.com/chennainetusergroup/july21stsessionregistration.msnw" target="_blank"><span style="font-family: Calibri;font-size: 11pt">http://groups.msn.com/chennainetusergroup/july21stsessionregistration.msnw</span></a><span style="font-family: Calibri;font-size: 11pt"> </span></p>
<p style="margin: 0in;font-family: Calibri;font-size: 11pt"> </p>
<p style="margin: 0in;font-family: 'Trebuchet MS';font-size: 10pt">Madhu [Solutions Architect from Polaris Labs] is doing session on Windows Communication Foundation [WCF] on the same day.</p>
]]></content:encoded>
			<wfw:commentRss>http://logukrishnan.net/2007/07/16/session-on-wpf-for-chennai-net-ug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

