<?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>gavpugh.com &#187; XNA / C#</title>
	<atom:link href="http://www.gavpugh.com/category/xna-csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gavpugh.com</link>
	<description>A Videogame Programming Blog</description>
	<lastBuildDate>Wed, 21 Dec 2011 20:22:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>XNACPC: Xbox 360 Amstrad CPC Emulator, released!</title>
		<link>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/</link>
		<comments>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 17:44:54 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[amstrad cpc]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[xnacpc]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1173</guid>
		<description><![CDATA[On and off during the last month or so, I&#8217;ve worked toward finishing a project I wrote about last year. It&#8217;s an Amstrad CPC Emulator, written in C# using the Microsoft XNA library. I&#8217;ve written plenty about the background and motivation in the previous blog post. This post is just here to announce the finished [...]]]></description>
			<content:encoded><![CDATA[<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/xnacpc_title.png" alt="" title="xnacpc_title" width="449" height="211" class="aligncenter size-full wp-image-1175" /><br />
</center></p>
<p>On and off during the last month or so, I&#8217;ve worked toward finishing a project I wrote about <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">last year</a>. It&#8217;s an Amstrad CPC Emulator, written in C# using the Microsoft XNA library. I&#8217;ve written plenty about the background and motivation in the  <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">previous blog post</a>. This post is just here to announce the finished product, and touch a little on the things I&#8217;ve worked on recently.</p>
<p>The picture above is from Hewson&#8217;s &#8220;Nebulus&#8221;. Now that the emulator has a pretty complete feature set; games like these are very playable now. It makes a world of difference having the audio fully working now, for example. It also is great to finally be able to play at the original, full frame rate on Xbox 360. Surprisingly the 360 had trouble emulating this seemingly primitive machine! </p>
<p>Anyway, after the jump is a video showing the emulator in action on the 360&#8230;</p>
<p><span id="more-1173"></span></p>
<p>&nbsp; </p>
<h2>XNACPC In Action</h2>
<p>Here you go! This video shows a number of games running on the emulator. It&#8217;s taken with a point-and-shoot camera, in a poorly lit room. So the quality isn&#8217;t too great, unfortunately. Some games have pretty washed out colors and bad contrast; some look fine though.</p>
<p>I guess I could have captured it from my PC, but the whole point of the emulator was to get it running on the Xbox 360. The fun part is showing it off on the real thing. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p></p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/TfB2V1DmFs0" frameborder="0" allowfullscreen="1"></iframe></p>
<h2>CRTC &#8211; Good Timing and Accurate Video</h2>
<p>My first pass at XNACPC <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">last year</a>, used the same technique which I employed when I wrote my CPC emulator back in the 90&#8242;s. I used a pretty naive approach, that had surprisingly good results for the early crop of launch games for the CPC.</p>
<p>I fudged the interrupts simply so that they occurred at 300Hz, which they&#8217;d be at on a real CPC. I wasn&#8217;t emulating the HSYNC correctly, nor the counters which are based off the HSYNC and generate interrupts. I also had to fudge the VSYNC signal which is read from one of the PPI ports. Whilst it was a primitive approach, it worked pretty well. Even &#8216;Sorcery&#8217;; a split-screen game, looked and played like the original.</p>
<p>Fixing the CRTC to behave properly was at the top of my list. I was pleased that I managed it. The best reference I found for it was probably here:</p>
<ul>
<li><a href="http://www.grimware.org/doku.php/documentations/devices/crtc">http://www.grimware.org/doku.php/documentations/devices/crtc</a></li>
</ul>
<div align=center><b><i><br />
<a href="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_timing.png" target="_blank"><img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_timing-300x187.png" alt="" title="crtc_timing" width="300" height="187" class="aligncenter size-medium wp-image-1177" /></a><br />Grimware CRTC Timing Reference<br /></b></i></div>
<p>&nbsp;</p>
<p>So I threw away my old video implementation and did it the proper way. Many games which previously didn&#8217;t work, now played just fine. I also used to draw the entire screen at the end of the frame. When I switched to drawing it line-by-line after each HSYNC, it eliminated flickering artifacts in many games. &#8220;Monty on the Run&#8221; for instance, looked awful in many places when I was updating the whole screen at once.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_bug.png" alt="" title="crtc_bug" width="457" height="147" class="aligncenter size-full wp-image-1178" /><br />&#8220;Monty On The Run&#8221; &#8211; Fullscreen vs. Line-by-line<br /></b></i></div>
<p>&nbsp;</p>
<h2>Audio &#8211; Silence Isn&#8217;t Golden</h2>
<p>I actually traded off the audio work with the CRTC work. I&#8217;d switch between them when I hit a wall, to keep things interesting. When I first worked on the emulator last year it actually wasn&#8217;t possible to implement emulated audio at all. That only became possible when XNA 4.0 was released, with the addition of <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.dynamicsoundeffectinstance.aspx" target="_blank">DynamicSoundEffectInstance</a>.</p>
<p>The audio on a CPC is pretty simple in it&#8217;s concept, but it did take me a little while to get the timing correct. It&#8217;s essentially based on square waves, where the audio signal is either on or off. The signal does have volume control, so it&#8217;s possible to produce pretty decent sounding music with it.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/square_wave.png" alt="" title="square_wave" width="482" height="241" class="aligncenter size-full wp-image-1179" /><br />AY8912 Audio Square Waves<br /></b></i></div>
<p>&nbsp;</p>
<p>There&#8217;s three main parts to the AY audio chip used in the CPC:</p>
<ul>
<li>Three channels of tone generators. Producing square waves at given independent periods.</li>
<li>A single noise generator. It generates random noise, which can be used by any combination of channels instead of the tone generator output.</li>
<li>A single envelope generator. This allows any combination of channels to progressively change the volume over time, in a manner that doesn&#8217;t need any CPU assistance.</li>
</ul>
<p>Of the three channels; two of them represent the left and right speakers, and the other one is mixed between each speaker.</p>
<p>That&#8217;s the gist of it. The audio was pretty satisfying to implement; since I&#8217;d never tried to get it working, back in the emulator I developed in the 90&#8242;s. Unfortunately the addition of the audio was taxing enough for the Xbox to drop under the 50fps that a CPC runs at. This meant I had to refactor the audio code somewhat, from a nice C#-style to a more brute-force C-style. </p>
<h2>Z80, PPI and Other Hardware Bugs</h2>
<p>There was a fun little period after I had the CRTC emulation all working correctly. With the last big hurdle overcome, I now had to fix bugs in my hardware implementation. This was the period where suddenly lots of other dead non-working games would spring to life.</p>
<p>Coming back to the source code after over a year was fine for the most part, but I did forget about a number of functions which I stubbed out. The PPI was a big one, I just did the basics to get the most primitive games running. So there I had to go back to the hardware documents and fill in the more obscure parts of the implementation. After doing that, a bunch more games would run.</p>
<p>One other key fix I remember was to the Z80 emulation. The HALT instruction was broken. I took the Z80 CPU emulator originally from an older <a href="http://zx360.codeplex.com/" target="_blank">C# Spectrum emulator</a>. I&#8217;d made a number of modifications to get it to play nice with the CPC; mostly around timing and interrupts. When I noticed a couple of games dying on the HALT instruction, I went back to the Z80 documentation and implemented HALT correctly. As well as getting some games to run, it also amusingly fixed the broken &#8216;pelvic thrust&#8217; animation in the intro to &#8216;Rocky Horror Picture Show&#8217;. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/rocky_horror.png" alt="" title="rocky_horror" width="420" height="156" class="aligncenter size-full wp-image-1180" /><br />&#8220;The Rocky Horror Picture Show&#8221; &#8211; Intro<br /></b></i></div>
<p>&nbsp;</p>
<h2>CRT Shader &#8211; A Bit of Polish</h2>
<p>Once I finally had the majority of the games looking pretty much perfect, I had an inkling to go a little further. I&#8217;m not much of a graphics programmer, by today&#8217;s standards. I used to be really into graphics programming back in the mid to late 90&#8242;s. Michael Abrash&#8217;s <a href="http://www.amazon.com/Zen-Graphics-Programming-Ultimate-Writing/dp/188357708X" target="_blank">&#8220;Zen of Graphics Programming&#8221;</a> was one of my favorite books. I also remember fondly working through the <a href="http://bespin.org/~qz/pc-gpe/" target="_blank">&#8216;Asphixia VGA Trainers&#8217;</a>. It&#8217;s about the last time I think I wrote more than just a handful of lines of assembly code at once. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It&#8217;d been a few years since I last experimented with shaders, so I decided to try writing a simple shader to give the emulator a <a href="http://filthypants.blogspot.com/2011/05/more-emulator-pixel-shaders-crt-updated.html" target="_blank">&#8216;CRT effect&#8217;</a>. I only spent a small amount of time on it; it&#8217;s nothing fancy. The gist of my effect works as follows:</p>
<ul>
<li>Each CPC pixel is exactly three &#8216;XNA pixels&#8217; high. My shader uses modf() to modolo based on this, so I can do something different for each of the three rows of pixels.</li>
<li><b>Row One:</b> I leave the color alone. Sample goes straight through.</li>
<li><b>Row Two:</b> 90% of the color I take from original sampled value. 5% I actually sample from the next CPC pixel scanline. Then, 5% left out to make it darker. </li>
<li><b>Row Three:</b> 75% of the color I take from original sampled value. 15% I sample from the next scanline. Then, 10% left out to make it darker.</li>
</ul>
<p>Sampling a little of the next scanline down, introduces a little color bleeding; which seems to work well. It&#8217;s pretty decent-looking considering how simple my shader was. Here&#8217;s a zoomed picture, below. It looks it&#8217;s best though at 1:1 resolution, as you can see from the &#8220;Nebulus&#8221; shot at the very top of this blog post.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crt_shader.png" alt="" title="crt_shader" width="640" height="388" class="aligncenter size-full wp-image-1181" /><br />&#8220;Ikari Warriors&#8221; &#8211; 2x Zoomed Shot of my CRT Shader Effect<br /></b></i></div>
<p>&nbsp;</p>
<h2>Xbox 360 &#8211; Compact Framework Creaking Under Pressure</h2>
<p>Getting the emulator running at the full frame rate of the original CPC, wasn&#8217;t much fun. On PC it was fine, no problems there. I think Task Manager shows ~2% CPU usage on my PC when it&#8217;s running. When I turned the frame-rate limiting off, I think it ran at >300fps. I&#8217;m talking specifically here about emulation of the CPC, not just drawing and updating the screen. So when I run it with the frame-limiter off, the machine runs so fast that any game is essentially unplayable.</p>
<p>Now, the Xbox 360. Some of you with experience with C# and the 360, will likely think I&#8217;ll mention garbage collection? Actually this wasn&#8217;t an issue for me. For any emulation runtime code, I made sure I wasn&#8217;t doing anything bad there. I generate absolutely no garbage when the game runs. I do allow for garbage in my &#8220;Pause Menu&#8221; code, however. But that&#8217;s really nice and easy to handle, just perform a full collection when unpausing. I like that approach for being able to write quick-and-dirty UI code, and keep the actual game clean.</p>
<p>So, not garbage? Nah, it&#8217;s just a raw CPU throughput problem. I hear someone shouting &#8220;JIT&#8221;&#8230;? Indeed; it does help a lot. The version of the emulator I&#8217;ve uploaded today runs at about half the speed of a CPC, when I have the debugger attached to the Xbox. So yeah: Release Build. No debugger attached. No garbage collection. This is as good as it gets.</p>
<p>I did a few things to drag the emulator kicking and screaming, to meet the 50fps that the CPC runs at:</p>
<ul>
<li>General optimizations which seem to benefit 360: Lookup tables seem to win over a handful of computational instructions. A general mistrust of the optimizer/JIT works well too. Cache variables yourself when doing multiple lookups from other classes, for example.</li>
<li>Changed the routine which writes screen memory out to the XNA texture, to use unsafe code.</li>
<li>Refactored my audio code to have the tone, noise and envelope generators as structs instead of classes (no vcalls). Ripped out my nice methods and just let my audio code access public members instead.</li>
<li>The biggest win by far was hand-unrolling a simple for loop. It was an inner loop inside my graphics rendering code. It was walking over eight pixels for each byte of CPC memory. Instead of looping, I copy and pasted the line over eight times. My frame rate jumped from ~40fps to ~50fps.</li>
</ul>
<p>Anyway. This was a bit of an eye-opener. I&#8217;m used to writing native code on 360, and I&#8217;m sure the thing wouldn&#8217;t break a sweat with a C++ version of my emulator. It&#8217;s odd to think that when I first worked on my emulator back in 1998, in C++; it was on a Pentium 120. That P120 ran the emulation fine, taxing the CPU at around 50% if I recall. Compare that to the ~95% I&#8217;m shipping XNACPC on the Xbox with. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, the Compact Framework on 360 isn&#8217;t too hot. To be honest though, I&#8217;d have no qualms with developing something like this in C# if I was targeting PC. The full .NET Framework seems to be a good performer. Of course, straight-game code is going to be a whole different kettle of fish; compared to something as ridiculous as I&#8217;ve coded here. I don&#8217;t mean to slag off the Compact Framework; I&#8217;d imagine other XNA devs don&#8217;t see the huge disparity that I did, when they&#8217;re coding their games.</p>
<h2>The Source</h2>
<p>In an ideal world I&#8217;d be able to release it on the XBLIG channel. But given both copyright (and moral) issues with distributing games that other people have worked on, it&#8217;s not a possibility. This is a shame for people interested in playing with it though, since it means your only option requires a &#8216;Creators Club&#8217; subscription. This costs $99 a year!</p>
<p>That said, I&#8217;d likely expect the few of you that actually read this blog (and the fewer that read this far down!) might be XNA coders. I&#8217;ve a zip file setup which contains the solution and project files, with the emulator ready to deploy to your Xbox. You can download it here:<br />
<a href="http://www.gavpugh.com/xnacpc/xnacpc_1_0_source.zip"><img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2010/04/zip_file1.png" alt="Zip File" width="48" height="52" /><strong> xnacpc_1_0_source.zip</strong></a></p>
<p>If you just want to browse the code online, I&#8217;ve put it up here at Google Code too:</p>
<ul>
<li><a href="http://code.google.com/p/xnacpc/" target="_blank">Google Code &#8211; XNACPC</a></li>
</ul>
<p>If you&#8217;re interested in taking XNACPC and releasing something (legal and authorized) on XBL Indie Games, or Windows Phone 7. Please contact me about it, I&#8217;d love to work on the project!</p>
<h2>PC Version</h2>
<p>The PC version is playable without any sort of coding experience, nor requiring paying any money to Microsoft. You can download it here:<br />
<a href="http://www.gavpugh.com/xnacpc/xnacpc_1_0_pc_binaries.zip"><img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2010/04/zip_file1.png" alt="Zip File" width="48" height="52" /><strong> xnacpc_1_0_pc_binaries.zip</strong></a></p>
<p>Just unzip it somewhere, and run &#8216;XNACPC.exe&#8217;. That&#8217;s it. There&#8217;s a number of games in the package, all setup ready to play. You may also need to download the <a href="http://www.microsoft.com/download/en/details.aspx?id=20914" target="_blank">XNA Runtime</a>, if the app complains about missing something when you run it.</p>
<h2>What&#8217;s Next?</h2>
<p>Well, I really don&#8217;t plan to do any more work on XNACPC. There&#8217;s plenty of other CPC emulators which are more complete. They emulate more features, and run pretty much any game you can throw at them. The intention wasn&#8217;t to compete with those emulators, it was just to prove it&#8217;s possible to do the same in C# with XNA. I think I&#8217;ve done that, so there&#8217;s no real motivation to continue with the project.</p>
<p>It&#8217;s been fun; but I&#8217;ve been tinkering with CPC emulators in various forms since 1998. Right now I&#8217;m happy to close the door on this, and keep working on &#8216;new&#8217; stuff instead of having one eye on the past. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hope you enjoy poking around the <a href="http://code.google.com/p/xnacpc/" target="_blank">source code</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; StringBuilder changes in XNA 4.0</title>
		<link>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/</link>
		<comments>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 19:00:18 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FieldAccessException]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[System.Text.StringBuilder]]></category>
		<category><![CDATA[windows 7 phone]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=967</guid>
		<description><![CDATA[So yeah, this is another post detailing a change made in the latest version of XNA. This one was inspired by some comments on a previous blog post of mine: &#8220;StringBuilder to String with no garbage&#8221;. A developer named Matt, who was targeting Windows 7 Phones, pointed out that this particular trick with reflection was [...]]]></description>
			<content:encoded><![CDATA[<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/StringHeader.png" alt="StringBuilder" title="StringBuilder" width="450" height="283" class="aligncenter size-full wp-image-972" /><br />
</center></p>
<p>So yeah, this is another post detailing a change made in the latest version of XNA.</p>
<p>This one was inspired by some comments on a previous blog post of mine: <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">&#8220;StringBuilder to String with no garbage&#8221;</a>. A developer named Matt, who was targeting Windows 7 Phones, pointed out that this particular trick with reflection was not working. He&#8217;d get a &#8216;FieldAccessException&#8217; when attempting to access the internal private System.String object.</p>
<p>I&#8217;d just got round to installing the Windows Phone stuff to check this out, and indeed this is the case. I tried various different flags in the GetField() call, but had no luck in getting it to work. I tried setting up a trivial case with my own class containing a private &#8216;System.String&#8217; and had the exact same problem.</p>
<p><span id="more-967"></span></p>
<p>So for whatever reason Windows Phone&#8217;s Compact Framework doesn&#8217;t allow access to private members via the GetValue() reflection call. In my aforementioned test with my own custom class, public members worked fine. In both cases the GetField() method was all good, it was just the GetValue() that throws &#8216;FieldAccessException&#8217; in the case of private members.</p>
<p>Well&#8230; That&#8217;s a bit of a fly in the ointment right there. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h3>Windows PC: A totally new version of StringBuilder?</h3>
<p>Upon further inspection with the new XNA, I saw that the Windows setup had changed too. The StringBuilder object contents had changed completely. </p>
<p>For reference, here&#8217;s what I&#8217;ll call &#8216;version one&#8217; of the StringBuilder. The one we&#8217;re used to from good &#8216;ol XNA 3.1:<br />
<center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/SBPhone40.png" alt="StringBuilder_v1" title="StringBuilder_v1" width="292" height="120" class="alignnone size-full wp-image-981" /><br />
<i>StringBuilder version one</i><br />
</center></p>
<p>Here&#8217;s &#8216;version two&#8217;:<br />
<center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/SBWindows40.png" alt="StringBuilder_v2" title="StringBuilder_v2" width="295" height="171" class="alignnone size-full wp-image-982" /><br />
<i>StringBuilder version two</i><br />
</center><br />
</p>
<p>Very, very different. </p>
<p>This new version maintains a series of chunks. As chunks are added it actually ends up linking together multiple new StringBuilder objects. The member &#8216;m_ChunkPrevious&#8217; is this link.</p>
<p>From checking out the XNA 4.0 platforms, only the PC Windows build target uses this new StringBuilder. It could be argued that given that the GC performs well on PC that you need not use any tricks to grab internal strings anyway.</p>
<p>If you&#8217;re desperate though, I did come up with a crude method of grabbing the internal string without generating garbage. Be warned though, it&#8217;s far uglier than the previous &#8217;3.1&#8242; method I had.</p>
<p>Here goes:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> MAX_STRING_SIZE <span style="color: #008000;">=</span> <span style="color: #FF0000;">64</span><span style="color: #008000;">;</span>
&nbsp;
StringBuilder my_string_builder<span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> my_char_array<span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> my_dest_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">' '</span>, MAX_STRING_SIZE<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">unsafe</span> <span style="color: #6666cc; font-weight: bold;">void</span> CopyIntoString<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">string</span> dest_string, <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> char_buffer, <span style="color: #6666cc; font-weight: bold;">int</span> length <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Debug</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Assert</span><span style="color: #008000;">&#40;</span> dest_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;=</span> length <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">unsafe</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">fixed</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">*</span> dest_fixed <span style="color: #008000;">=</span> dest_string <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// Copy in the string data</span>
                <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> length<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    dest_fixed<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> char_buffer<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// NULL terminate the dest string</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> length <span style="color: #008000;">&lt;</span> dest_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    dest_fixed<span style="color: #008000;">&#91;</span>length<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#41;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> PrepareSB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>            
    my_string_builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span>MAX_STRING_SIZE, MAX_STRING_SIZE<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Ensure this StringBuilder only has one chunk</span>
    StringBuilder sanity_check <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>StringBuilder<span style="color: #008000;">&#41;</span>my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
        <span style="color: #666666;">&quot;m_ChunkPrevious&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>my_string_builder<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Debug</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Assert</span><span style="color: #008000;">&#40;</span> sanity_check <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Grab the char array from the StringBuilder</span>
    my_char_array <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
        <span style="color: #666666;">&quot;m_ChunkChars&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>my_string_builder<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//! This function can be called iteratively and generates no garbage</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> TestSB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Put something in there</span>
    my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Hello World!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Copy into our dest string</span>
    CopyIntoString<span style="color: #008000;">&#40;</span>my_dest_string, my_char_array, my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Note this dest string is a little odd, the NULL terminator shows in the </span>
    <span style="color: #008080; font-style: italic;">// debugger with all the spaces after it.</span>
    <span style="color: #008080; font-style: italic;">// On use of the string though in code, I'm seeing the correct amount of </span>
    <span style="color: #008080; font-style: italic;">// characters used. It stops at the NULL.</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>My eyes! <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It works&#8230; But really; I wouldn&#8217;t touch this monstrosity.<br />
&nbsp;<br />
</p>
<hr />
&nbsp;<br />
</p>
<h1>Summary by Version and Platform</h1>
<p>&nbsp;<br />
<br />
So what follows here is a summary of the version of StringBuilder used on each platform, under both XNA 3.1 and 4.0. I also note the version of &#8216;mscorlib&#8217; as listed in the project references section; this is the assembly which contains the System.Text.StringBuilder class.</p>
<h3>Visual Studio 2008, and XNA v3.1</h3>
<h4>Windows</h4>
<p><b>mscorlib v2.0.0.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<h4>Xbox 360</h4>
<p><b>mscorlib v3.5.0.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<h3>Visual Studio 2010, and XNA v4.0</h3>
<h4>Windows Phone 7</h4>
<p><b>mscorlib v2.0.5.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. Unfortunately reflection access to the internal System.String is disallowed. You&#8217;re stuck with using ToString() and incurring garbage.</p>
<h4>Windows</h4>
<p><b>mscorlib v4.0.0.0, Runtime Version v4.0.30319</b><br />
Uses StringBuilder version <strong>two</strong>. This new implementation of StringBuilder requires a convoluted way of converting the StringBuilder to a System.String, without generating garbage. I&#8217;d say incurring the garbage hit on PC is preferable to using the hacky stuff I&#8217;ve published in this post.</p>
<h4>Xbox 360</h4>
<p><b>mscorlib v2.0.5.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<p>Oddly enough the main version number dropped to v2.0.5.0, from v3.5.0.0. A little confusing. The versions though match the Windows Phone 7 assemblies exactly.</p>
<h3>Conclusions</h3>
<p>So, under XNA 4.0 you&#8217;re out of luck on Windows Phone 7 unfortunately. Please let me know though if this isn&#8217;t the case, if you find some other way of getting round it please drop a comment on this post.</p>
<p>For Xbox 360 we&#8217;re fortunately still good to use the same methods which worked under XNA 3.1.</p>
<p>It&#8217;s pretty much inevitable though that in future both Phone 7 and Xbox 360 are bumped up to the new .NET StringBuilder class, which Windows currently uses. Possibly even Xbox 360 may get the same reflection shackles that Phone 7 has now too.</p>
<p>Can only hope that when we get a new Compact Framework, it comes with a shiny new generational garbage collector implementation. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>References</h3>
<ul>
<li><a href="http://www.nesterovsky-bros.com/weblog/2010/08/25/StringAndStringBuilderInNET4.aspx" target="_blank">String and StringBuilder in .NET 4</a></li>
<li><a href="http://stackoverflow.com/questions/3564906/how-the-stringbuilder-class-is-implemented-does-it-internally-create-new-string" target="_blank">How the StringBuilder class is implemented? Does it internally create new string objects each time we append?</a></li>
<li><a href="http://stackoverflow.com/questions/4166155/does-stringbuilder-become-immutable-after-a-call-to-tostring" target="blank">Does StringBuilder become immutable after a call to ToString?</a></li>
<li><a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">XNA/C# – StringBuilder to String with no garbage</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Thread-local storage on Xbox 360</title>
		<link>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 17:48:53 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[LocalDataStoreSlot]]></category>
		<category><![CDATA[Thread-Local Storage]]></category>
		<category><![CDATA[threadlocal]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=891</guid>
		<description><![CDATA[&#160; I initially begun writing this particular article back in April. Back then with XNA 3.1 to play with, there was actually a method of &#8216;thread-local storage&#8217; for Xbox. With the release of XNA 4.0, this last remaining native method was removed. The [ThreadLocal] attribute though was added to the Compact Framework, but it seems [...]]]></description>
			<content:encoded><![CDATA[<p><center><img class="alignnone size-full wp-image-893" title="Thread-local storage" src="http://www.gavpugh.com/wp-content/uploads/2010/11/threadlocalstore.jpg" alt="Thread-local storage" width="400" height="277" /></center></p>
<p>&nbsp;</p>
<p>I initially begun writing this particular article back in April. Back then with XNA 3.1 to play with, there was actually a method of &#8216;thread-local storage&#8217; for Xbox. With the release of XNA 4.0, this last remaining <a href="http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/">native method was removed</a>. The [ThreadLocal] attribute though was added to the Compact Framework, but it seems to be a <a href="http://www.gavpugh.com/2010/11/26/xnac-%E2%80%93-threadstatic-attribute-is-broken-on-xbox-360/">stubbed non-functional attribute</a> on Xbox 360.</p>
<p>So, where does that leave us? There is various ways you can manually code up a thread-local storage solution. The whole crux of it is data-retrieval and storage on a per-thread basis. The most immediately obvious way to go is just some sort of associative container, a Dictionary<> of some sort of thread &#8216;id&#8217; mapped to the data you wish to store.</p>
<p><span id="more-891"></span></p>
<p>Just something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Dictionary<span style="color: #008000;">&lt;</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Threading</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Thread</span>, MyClass <span style="color: #008000;">&gt;</span> my_tls_data<span style="color: #008000;">;</span></pre></div></div>

<p>There&#8217;s a lot of room for freedom in implementation though. Is Dictionary<> really the most suitable container? Should items be auto-created on the first access, or explicitly created by the user? Most of all I want to keep things performing well. Given some functionality performs <a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">extremely poorly on the Xbox 360</a>, I want to be careful what I throw into my implementation.</p>
<h3>The profiling approach</h3>
<p>So, here&#8217;s how I set things up to profile changes I made throughout development:</p>
<ul>
<li>My test case sets up ten threads.</li>
<li>Each thread has TLS data which consists of one simple integer.</li>
<li>I kick off all ten threads at once, and each runs a loop 100,000 times incrementing their integer by one each time. (I verified the loop is not optimized out for the release-JIT&#8217;d builds).</li>
<li>Once I see all ten threads have finished their loops I conclude the test and take the timing.</li>
<li>I run the tests over and over and calculate a running average time. I display the results on screen, as opposed to debug output. So I can see the results on a release build which isn&#8217;t connected to the debugger. Pretty simple stuff, it just looks like this:<br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/11/profiling.png" alt="TLS Profiling" title="TLS Profiling" width="504" height="71" class="aligncenter size-full wp-image-947" />
</li>
<li>Xbox times have a steady average very quickly after just a dozen or so tests. Windows times were more erratic and I generally left them for a couple of minutes to settle down.</li>
</ul>
<h3>Implementation choices</h3>
<p>So, given the myriad of different ways this thing could be done, I broke down the choices I&#8217;d need to make. Here&#8217;s a breakdown piece-by-piece of the decisions I made along the way. Forgive the language, they&#8217;re just lifted verbatim from notes I made:</p>
<ul>
<li><strong>Array over Dictionary<></strong></li>
<ul>
<li>For both Windows and Xbox with ten test threads, using an array instead of a Dictionary<> was a little over twice as fast. 74ms versus 151ms on Xbox.</li>
<li>From additional testing on Xbox, array became a comparable speed to Dictionary<> at around 32 threads. I threw in a couple of different access patterns to test with too. Only if you&#8217;re going crazy with threads and data access, will Dictionary<> be a win.</li>
<li>See the source code for the array implementation. It&#8217;s just essentially a simple associative container of &#8216;Thread&#8217;->&#8217;Data&#8217;. Potentially the whole array needs to be searched on each access. But keeping the array size small makes this a win over Dictionary<>.</li>
</ul>
<li><strong>For vs foreach on array access</strong></li>
<ul>
<li>A for loop incrementing an integer was faster.</li>
<li>Doing the search with foreach() instead roughly doubled the times. 74ms versus 141ms.</li>
</ul>
<li><strong>Thread object vs integer thread ID (ManagedThreadId)</strong></li>
<ul>
<li>Each of these approaches were within a millisecond of one other. Something like 73.5ms versus 74ms. The integer version was the slight winner.</li>
<li>I kind of like using the object reference, it makes debugging easier. So I went with that instead of using the integer ID.</li>
</ul>
<li><strong>Call to Thread.CurrentThread on data access.</strong></li>
<ul>
<li>Cost is prohibitive on Xbox, see a blog post I wrote a while back:<br /><a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/</a></li>
<li>This is still the case under XNA 4.0, figures haven&#8217;t changed. For the testing I was doing for these classes, calling Thread.CurrentThread on Xbox each access increases the time taken in one example from 74ms up to 7248ms. The equivalent test on Windows went from 26ms up to 32ms.</li>
<li>My class has to provide a data accessor which takes a thread object param.</li>
</ul>
<li><strong>Explicit cleanup, versus WeakReference to determine threads are done with.</strong></li>
<ul>
<li>WeakReference is slow on Xbox unfortunately too. Even worse than Thread.CurrentThread in my tests. The example case I used shot up from 74ms to over 40,000ms. Windows jumped from 26ms to 76ms.</li>
<li>I chose to use explicit cleanup. </li>
<li>Side note: To make cleanup easier on thread destruction, consider a TLS manager class. The TLS objects can register with the manager upon creation, and the manager can walk them all destroy any data associated to a specific thread.</li>
</ul>
<li><strong>Explicit construction, versus &#8216;auto&#8217; construction.</strong></li>
<ul>
<li>Auto construction isn&#8217;t too much of a performance drop. It just adds an extra branch to the code if the data access fails to find its data. Which you probably would have in there anyway to throw an Exception, or fire an assert.</li>
<li>In my tests removing auto construction from my code, dropped the reference 74ms case down to 73ms. Good tradeoff in my opinion, so I kept auto-construction.</li>
</ul>
<li><strong>Avoid thread locks for data access</strong></li>
<ul>
<li>Locks are only required for adding new array entries, or removing them. The data access function should be able to execute in the general case without a lock.</li>
<li>With auto-construction though, a new entry could be added within the accessing function. There&#8217;s a risk of a race condition if two concurrent threads try to auto-construct the data for one specific thread.</li>
<li>As long as we can be sure that threads only access their own data, everything is fine. So the GetData(Thread) version should verify that the thread matches Thread.CurrentThread.</li>
<li>The check only needs to be made after the search fails, just as it&#8217;s about to do the auto-construction. I ended up just putting this code within #if DEBUG, so I didn&#8217;t have to worry about any performance hit.</li>
</ul>
</ul>
<h3>Explicit cleanup</h3>
<p>I wasn&#8217;t too happy with requiring explicit cleanup. It means the cleanest solution would be some kind of global static function which ensured all various TLS variables are freed. Something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> CleanupTLS<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    Profiler<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentNodeStack</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">Output</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetStringBuilder</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Renderer<span style="color: #008000;">.</span><span style="color: #0000FF;">DebugLines</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// etc...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Consider too that some of these variables may be initially at private scope, so they would need to be specifically exposed somehow so the freeing can occur. At best you&#8217;d need to add explicit public freeing functions to various affected modules.</p>
<p>As hinted in my notes, a global manager class which registers all TLS variables could make this a lot cleaner. As TLS data is instantiated, I will register with the manager. Where this occurs is not performance-critical. The freeing isn&#8217;t performance-critical either. The freeing though is pretty simple, the manager just walks all the TLS references it&#8217;s been given, and attempts to purge any with data for a specific thread.</p>
<p>So instead of calling the above mess, you can just call:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocalManager</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Bit happier with it now. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Profiling figures</h3>
<p>I explained my profiling setup earlier in this article. Here are the figures with my final implementation, compared against the existing methods of TLS. The &#8216;No param&#8217; version of my code makes a call to &#8216;Thread.CurrentThread&#8217; each time to determine what data to pass back. The &#8216;Thread param&#8217; version uses a passed in thread reference to retrieve the data instead.</p>
<p>The figures are for ten concurrent threads making 100,000 accesses each:</p>
<table border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr height="20">
<td width="300" height="20"></td>
<td align="center" colspan="2"><b>Windows PC</b></td>
<td align="center"colspan="2" ><b>Xbox 360</b></td>
</tr>
<tr height="20">
<td height="20"></td>
<td width="180" align="center">Release &#8211; <br />Debugger</td>
<td width="180" align="center">Release &#8211; JIT&#8217;d</td>
<td width="180" align="center">Release &#8211; <br />Debugger</td>
<td width="180" align="center">Release &#8211; JIT&#8217;d</td>
</tr>
<tr height="20">
<td height="20"><strong>My code &#8211; No param</strong></td>
<td align="right">152.3ms</td>
<td align="right">31.2ms</td>
<td align="right"><b>*</b> 7805.9ms</td>
<td align="right"><b>*</b> 7248.8ms</td>
</tr>
<tr height="20">
<td height="20"><strong>My code &#8211; Thread param</strong></td>
<td align="right">139.4ms</td>
<td align="right">27.9ms</td>
<td align="right">456.8ms</td>
<td align="right">74.2ms</td>
</tr>
<tr height="20">
<td height="20"><strong>[ThreadStatic]</strong></td>
<td align="right">172.7ms</td>
<td align="right">45.6ms</td>
<td align="right">N/A</td>
<td align="right">N/A</td>
</tr>
<tr height="20">
<td height="20"><strong>GetData/SetData()</strong></td>
<td align="right">164.3ms</td>
<td align="right">51.1ms</td>
<td align="right"><b>**</b> 7854.1ms</td>
<td align="right"><b>**</b> 7565.3ms</td>
</tr>
</tbody>
</table>
<p>&nbsp;<br />
<i>* Using &#8216;Thread.CurrentThread&#8217; on Xbox 360 <a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">is very slow</a>.</i><br />
<i>** The GetData/SetData() (LocalDataStoreSlot) method doesn&#8217;t work under XNA 4.0 on Xbox 360. These figures are from when I ran the same tests months ago under XNA 3.1 on 360.</i></p>
<p>Given these figures I&#8217;m happy to use my new implementation for both Windows and Xbox 360. There&#8217;s no alternatives currently for Xbox 360, so given I&#8217;ve explored many optimization possibilities it&#8217;s pretty much as good as it gets. For Windows it actually is slightly faster than even [ThreadStatic], so using the same code across both totally makes sense.</p>
<h3>Show me the code</h3>
<p>Here&#8217;s the code for download:<br />
<a href="http://www.gavpugh.com/source/ThreadLocal.cs"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="cs_file" src="http://www.gavpugh.com/wp-content/uploads/2010/03/cs_file1.png" alt="C# File" width="48" height="52" /><strong>ThreadLocal.cs</strong></a></p>
<p>It also includes the class for &#8216;ThreadLocalManager&#8217;, which as detailed earlier assists with easier cleanup of data from destroyed threads.</p>
<p>Here&#8217;s a quick contrived bit of code to show how these classes should be used:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocal</span><span style="color: #008000;">&lt;</span>StringBuilder<span style="color: #008000;">&gt;</span> ms_tls_stringbuilder <span style="color: #008000;">=</span> 
    <span style="color: #008000;">new</span> Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocal</span><span style="color: #008000;">&lt;</span>StringBuilder<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//! Entry function for new worker threads</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> ThreadRun<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Grab the TLS stringbuilder</span>
    StringBuilder sb <span style="color: #008000;">=</span> ms_tls_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Data</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Do bunch of work</span>
    <span style="color: #008000;">...</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Free all TLS data associated with this thread</span>
    Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocalManager</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The TLS data access has a function which takes a thread parameter. This should be used in performance-critical code, given my findings detailed in this article. Just note the &#8216;Thread.CurrentThread&#8217; once in your new thread, and pass it around to any performance-critical functions that require working with TLS.</p>
<h3>Value Types</h3>
<p>My implementation is currently tied to just using reference types, value types will not work with it. An alternative is to just simply wrap value types in a class, which is what I&#8217;ve been happy to do with my engine.</p>
<p>If you absolutely need a thread-local implementation which does work natively with value types, it&#8217;s not too hard to do. You&#8217;d want to set up an alternative class, with pretty much the same code in it. Change the &#8216;where&#8217; constraint to simply: <strong>&#8216;struct&#8217;</strong>. There&#8217;s a couple of different ways I could see the implementation going:</p>
<ul>
<li>Implement separate Get and Set data methods. Maybe just a single property?</li>
<li>Have a get method not return a value, but instead pass it back through a reference parameter.</li>
</ul>
<p>There&#8217;s no reason why you couldn&#8217;t have both these types of interface for it.</p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb203915.aspx" target="_blank">MSDN: Namespaces, Types, and Members in the .NET Compact Framework for Xbox 360</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/6sby1byh%28v=VS.100%29.aspx" target="_blank">MSDN: Thread Local Storage: Thread-Relative Static Fields and Data Slots</a></li>
<li><a href="http://forums.xna.com/forums/t/18202.aspx?PageIndex=1" target="_blank">XNA Forums: possible to have an array on stack, not in heap?</a></li>
<li><a href="http://forums.xna.com/forums/p/29351/164709.aspx" target="_blank">XNA Forums: Why no ThreadStaticAttribute on XNA?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" target="_blank">MSDN: Constraints on Type Parameters</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XNA/C# – [ThreadStatic] attribute is broken on Xbox 360</title>
		<link>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/#comments</comments>
		<pubDate>Sat, 27 Nov 2010 04:34:28 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[SetProcessorAffinity()]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[ThreadStaticAttribute]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=853</guid>
		<description><![CDATA[Continuing on from my last XNA post, I had a go at using [ThreadStatic] on the Xbox. Specifically this attribute was not available with XNA 3.1, but was introduced in the new 4.0 version. At first glace it worked fine, I threw in the same code I&#8217;d used on Windows. Unlike under 3.1 it compiles [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2010/11/Thread2.png" alt="[ThreadStatic]" title="[ThreadStatic]" width="400" height="241" class="alignnone size-full wp-image-871" /><br />
</center></p>
<p>Continuing on from <a href="http://http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/">my last XNA post</a>, I had a go at using <a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute%28v=VS.95%29.aspx" target="_blank">[ThreadStatic]</a> on the Xbox. Specifically this attribute was not available with XNA 3.1, but was introduced in the new 4.0 version.</p>
<p>At first glace it worked fine, I threw in the same code I&#8217;d used on Windows. Unlike under 3.1 it compiles without issue. However, the attribute appears to actually do nothing it all. It behaves just like the attribute wasn&#8217;t there, just like a regular plain static variable.</p>
<p>I found this issue from attempting to use [ThreadStatic] within some code I had written for a future article here. The code was to profile various methods of implementing <a href="http://en.wikipedia.org/wiki/Thread-local_storage" target="_blank">Thread-local storage</a> on the Xbox 360. Switching the code to add a test case for [ThreadStatic] worked fine at first, but I was seeing very odd profile numbers coming back from it. On closer inspection in the debugger I could see that the TLS values weren&#8217;t thread-specific, they were getting written to at runtime by other executing threads.</p>
<p><span id="more-853"></span></p>
<h3>Show me the code</h3>
<p>So, I spliced out some code and came up with a contrived test to check how [ThreadStatic] is working. Here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ThreadTest
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">&#91;</span>ThreadStatic<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_int_counter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> Thread m_thread<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_affinity<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_thread_num<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> ThreadTest<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> thread_num, <span style="color: #6666cc; font-weight: bold;">int</span> affinity <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_affinity <span style="color: #008000;">=</span> affinity<span style="color: #008000;">;</span>
        m_thread_num <span style="color: #008000;">=</span> thread_num<span style="color: #008000;">;</span>
        m_thread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span> Run <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Start<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span><span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Run<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">object</span> passed_obj <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        ThreadTest this_obj <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>ThreadTest<span style="color: #008000;">&#41;</span>passed_obj<span style="color: #008000;">;</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Started thread #&quot;</span> <span style="color: #008000;">+</span>
            this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; Affinity=&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_affinity</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080;">#if XBOX</span>
        Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SetProcessorAffinity</span><span style="color: #008000;">&#40;</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_affinity</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif //XBOX</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> 
            <span style="color: #666666;">&quot;Thread #&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> 
            <span style="color: #666666;">&quot;: Before m_int_counter &quot;</span> <span style="color: #008000;">+</span> m_int_counter <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        m_int_counter<span style="color: #008000;">++;</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> 
            <span style="color: #666666;">&quot;Thread #&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> 
            <span style="color: #666666;">&quot;: After m_int_counter &quot;</span> <span style="color: #008000;">+</span> m_int_counter <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// The four affinities that are okay to use. See:</span>
<span style="color: #008080; font-style: italic;">// http://msdn.microsoft.com/en-us/library/microsoft.xna.net_cf.system.threading.thread.setprocessoraffinity.aspx</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> m_affinities <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">4</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">bool</span> m_started <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Call this from anywhere, I just threw it in Update() in a new XNA game project</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Test<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> m_started <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Just do it once...</span>
        <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    m_started <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> NUM_THREADS <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
&nbsp;
    ThreadTest<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> threads <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadTest<span style="color: #008000;">&#91;</span>NUM_THREADS<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Create ten threads and kick them off near-enough at the same time.</span>
    <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> NUM_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">int</span> affinity <span style="color: #008000;">=</span> m_affinities<span style="color: #008000;">&#91;</span>i <span style="color: #008000;">%</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
        threads<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadTest<span style="color: #008000;">&#40;</span> i, affinity <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        threads<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3>What&#8217;s up</h3>
<p>Firstly, here&#8217;s the output under Windows. The &#8216;before&#8217; number is always zero, and the &#8216;after&#8217; is always one. The [ThreadStatic] variable is indeed unique to each thread instance.</p>
<h4>Windows</h4>
<pre>
Started thread #0 Affinity=1
Started thread #6 Affinity=4
Started thread #4 Affinity=1
Started thread #7 Affinity=5
Started thread #8 Affinity=1
Started thread #2 Affinity=4
Started thread #9 Affinity=3
Thread #7: Before m_int_counter 0
Thread #8: Before m_int_counter 0
Thread #0: Before m_int_counter 0
Thread #6: Before m_int_counter 0
Thread #4: Before m_int_counter 0
Thread #2: Before m_int_counter 0
Thread #9: Before m_int_counter 0
Thread #8: After m_int_counter 1
Thread #7: After m_int_counter 1
Thread #0: After m_int_counter 1
Thread #6: After m_int_counter 1
Thread #4: After m_int_counter 1
Thread #9: After m_int_counter 1
Thread #2: After m_int_counter 1
Started thread #5 Affinity=3
Started thread #3 Affinity=5
Started thread #1 Affinity=3
Thread #1: Before m_int_counter 0
Thread #1: After m_int_counter 1
Thread #5: Before m_int_counter 0
Thread #5: After m_int_counter 1
Thread #3: Before m_int_counter 0
Thread #3: After m_int_counter 1
</pre>
<p>&nbsp;<br />
Disregard the affinity value for Windows, it&#8217;s not used. Anyhow, here&#8217;s the Xbox output.</p>
<h4>Xbox 360</h4>
<pre>
Started thread #0 Affinity=1
Thread #5: Before m_int_counter 3
Thread #6: Before m_int_counter 3
Thread #3: Before m_int_counter 3
Thread #2: Before m_int_counter 3
Thread #7: Before m_int_counter 3
Thread #9: Before m_int_counter 3
Thread #0: Before m_int_counter 3
Thread #5: After m_int_counter 4
Thread #6: After m_int_counter 5
Thread #3: After m_int_counter 6
Thread #2: After m_int_counter 7
Thread #7: After m_int_counter 8
Thread #9: After m_int_counter 9
Thread #0: After m_int_counter 10
</pre>
<p>&nbsp;</p>
<p>The [ThreadStatic] variable is obviously not unique to each thread. It&#8217;s just behaving like a regular static. If I comment out the line which sets the thread affinity (which is Xbox-specific code), I get similar output.</p>
<p>What&#8217;s also concerning is that the &#8220;Debug.WriteLine()&#8221; function seems to be randomly failing. Each time I run it, I get different lines missed out from my expected output.</p>
<p>Perhaps on Xbox it&#8217;s implementation is not completely thread-safe? I swear it was on XNA 3.1&#8242;s Compact Framework, but maybe my memory is failing me.</p>
<h3>Solutions?</h3>
<p>I have an alternate way of implementing TLS with C#. It&#8217;s very fast as long as you&#8217;re not running a ridiculous number of threads (under a dozen is fine). When I last looked at the code under XNA 3.1 it outperformed the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.getdata.aspx" target="_blank">&#8216;GetData/SetData()&#8217;</a> method of TLS considerably. In fact when I tested the code under Windows and compared it to [ThreadStatic], it outperformed that too.</p>
<p>Will be the next article I post up, since I think I&#8217;ve encountered all the issues I can on the road to finishing it up.</p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute%28v=VS.95%29.aspx" target="_blank">ThreadStaticAttribute Class</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.net_cf.system.threading.thread.setprocessoraffinity.aspx" target="_blank">Thread.SetProcessorAffinity Method</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Changes in the Xbox 360 Compact Framework</title>
		<link>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/</link>
		<comments>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 18:03:11 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[Thread-Local Storage]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=805</guid>
		<description><![CDATA[A few months back I was partway through an article about XNA. I was going to cover how to implement efficient &#8220;Thread Local Storage&#8221; on the Xbox 360. Back in Game Studio v3.1 I found that the [ThreadStatic] attribute was not supported on the Xbox, and the only workable methods out of the box were [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2010/11/compactframework.jpg" alt="Compact Framework" title="Compact Framework" width="400" height="306" class="alignnone size-full wp-image-808" /><br />
</center></p>
<p>A few months back I was partway through an article about XNA. I was going to cover how to implement efficient <a href="http://en.wikipedia.org/wiki/Thread-local_storage" target="_blank">&#8220;Thread Local Storage&#8221;</a> on the Xbox 360. Back in Game Studio v3.1 I found that the <strong>[ThreadStatic]</strong> attribute was not supported on the Xbox, and the only workable methods out of the box were the Thread.GetData(), Thread.SetData() methods. Those methods aren&#8217;t good performance-wise, so I proceeded to look at more efficient alternatives.</p>
<p>That article was going to detail the solution I came up with, and currently used in my engine. However upon revisiting the work recently and upgrading to the new v4.0 XNA, I found that I had some compile errors. Specifically <strong>&#8216;System.Threading.LocalDataStoreSlot&#8217;</strong> was now missing, it&#8217;s that slow method of TLS I was using to benchmark against. So I commented that code out. I then figured why not for the hell of it try to enable the <strong>[ThreadStatic]</strong> code, that I had #ifdef&#8217;d to the WINDOWS build. Lo and behold, it now compiled on Xbox 360!</p>
<p><span id="more-805"></span></p>
<p>No idea if it&#8217;s any better performing than the old &#8216;LocalDataStoreSlot&#8217; though, or better than the alternate method I came up with. That&#8217;s an exercise for another day.</p>
<h3>My Googling Escapades</h3>
<p>The only article I could find back when I was working on 3.1 about [ThreadStatic] on Xbox was <a href="http://forums.create.msdn.com/forums/p/18202/96386.aspx" target="_blank">this</a> one. Doing a search now, I couldn&#8217;t find anything else new. I also tried searching for information about &#8220;LocalDataStoreSlot&#8221;, the class which was removed in the 4.0 upgrade. Again, I found nothing about the removal.</p>
<p>I also had noticed in some other code I have that the &#8216;System.Diagnostics.Trace&#8217; class, and static functions therein were also removed. Now I start to scratch my head a little and wonder what else has disappeared, and what other cool things may have been added. My searches weren&#8217;t very fruitful, I just found a handful of forum posts which mentioned briefly some sort of changes to the Compact Framework (I&#8217;ve included them in my references at the bottom of this page). Nothing complete and comprehensive which listed all the differences.</p>
<p>The MSDN documentation does denote on the page for each class, type, function&#8230; which platforms it is available on. There&#8217;s also a dropdown to switch the framework version. I confess I found it a bit unwieldy to check up on. For example &#8216;ThreadStaticAttribute&#8217; shows a &#8216;Silverlight&#8217; entry in the dropdown box. On that page it denotes that it works on the Xbox 360. Where &#8216;LocalDataStoreSlot&#8217; (the one which was removed), does not have Silverlight in it&#8217;s list, but does show XNA support for the 360 on the 3.5 Framework. Which tells me that it used to work, but now is deprecated in the Silverlight-compliant Framework.</p>
<p>Anyhow, checking these things one-by-one isn&#8217;t exactly viable.</p>
<h3>Taking a dump</h3>
<p>Knowing that there was a number of changes, but not knowing exactly what those changes were; I was still a little curious. What I did was to use the <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1%28VS.80%29.aspx" target="_blank">&#8216;ildasm&#8217; tool</a> to dump the types which existed in the .NET Framework DLL files.</p>
<p>For those equally curious, they reside here:<br />
<strong>C:\Program Files\Microsoft XNA\XNA Game Studio\v3.1\References\Xbox360</strong><br />
and here:<br />
<strong>C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360</strong><br />
Or wherever your &#8220;\Program Files&#8221; directory lies.</p>
<p>With a little tinkering I could collate that output and determine the changes which occurred between the two versions of the Framework. I omitted the <strong>&#8220;Microsoft.Xna.Framework.Input.Touch&#8221;</strong> library from the output though, since new Xbox 360 projects do not include it as a reference. I&#8217;m unsure though as to why there is a DLL sitting in the &#8220;Xbox 360&#8243; directory. Possibly early Natal/Kinect support code? Heh, I doubt it. I&#8217;m guessing it&#8217;s just stub functionality for parity with the Windows 7 phones.</p>
<p>So anyhow, here&#8217;s the data I collected. Hopefully others may find this useful&#8230; Or possibly just point me to a website that had this information already. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>System types <strong>removed</strong> from the Xbox 360 Compact Framework</h3>
<p>These are types which used to exist in the Compact Framework for the Xbox 360, in the &#8220;XNA Game Studio&#8221; v3.1 release. But these are now missing from the new v4.0 release:</p>
<pre>
  Microsoft.Xna.Framework.BatteryChargeStatus
  Microsoft.Xna.Framework.Graphics.BasicDirectionalLight
  Microsoft.Xna.Framework.Graphics.ClipPlane
  Microsoft.Xna.Framework.Graphics.ClipPlaneCollection
  Microsoft.Xna.Framework.Graphics.Color
  Microsoft.Xna.Framework.Graphics.CompilerOptions
  Microsoft.Xna.Framework.Graphics.DepthStencilBuffer
  Microsoft.Xna.Framework.Graphics.DeviceNotSupportedException
  Microsoft.Xna.Framework.Graphics.DeviceStillDrawingException
  Microsoft.Xna.Framework.Graphics.DeviceType
  Microsoft.Xna.Framework.Graphics.DriverInternalErrorException
  Microsoft.Xna.Framework.Graphics.EffectFunction
  Microsoft.Xna.Framework.Graphics.EffectFunctionCollection
  Microsoft.Xna.Framework.Graphics.EffectParameterBlock
  Microsoft.Xna.Framework.Graphics.EffectPool
  Microsoft.Xna.Framework.Graphics.GammaRamp
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/AddressCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/BlendCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/CompareCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/CursorCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DeclarationTypeCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DeviceCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DriverCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/FilterCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/LineCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/PixelShaderCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/PrimitiveCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/RasterCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/ShadingCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/StencilCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/TextureCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexFormatCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexProcessingCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexShaderCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCreationParameters
  Microsoft.Xna.Framework.Graphics.MultiSampleType
  Microsoft.Xna.Framework.Graphics.OutOfVideoMemoryException
  Microsoft.Xna.Framework.Graphics.PackedVector.Normalized101010
  Microsoft.Xna.Framework.Graphics.PackedVector.Rgba32
  Microsoft.Xna.Framework.Graphics.PackedVector.UInt101010
  Microsoft.Xna.Framework.Graphics.PixelShader
  Microsoft.Xna.Framework.Graphics.PresentOptions
  Microsoft.Xna.Framework.Graphics.QueryUsages
  Microsoft.Xna.Framework.Graphics.RasterStatus
  Microsoft.Xna.Framework.Graphics.RenderState
  Microsoft.Xna.Framework.Graphics.RenderTarget
  Microsoft.Xna.Framework.Graphics.ResolveTexture2D
  Microsoft.Xna.Framework.Graphics.ResourceType
  Microsoft.Xna.Framework.Graphics.SaveStateMode
  Microsoft.Xna.Framework.Graphics.ShaderConstant
  Microsoft.Xna.Framework.Graphics.ShaderConstantCollection
  Microsoft.Xna.Framework.Graphics.ShaderConstantTable
  Microsoft.Xna.Framework.Graphics.ShaderProfile
  Microsoft.Xna.Framework.Graphics.ShaderRegisterSet
  Microsoft.Xna.Framework.Graphics.SpriteBlendMode
  Microsoft.Xna.Framework.Graphics.StateBlock
  Microsoft.Xna.Framework.Graphics.SwapEffect
  Microsoft.Xna.Framework.Graphics.TextureUsage
  Microsoft.Xna.Framework.Graphics.TextureWrapCoordinates
  Microsoft.Xna.Framework.Graphics.VertexElementMethod
  Microsoft.Xna.Framework.Graphics.VertexShader
  Microsoft.Xna.Framework.Graphics.VertexStream
  Microsoft.Xna.Framework.Graphics.VertexStreamCollection
  Microsoft.Xna.Framework.Net.InviteAcceptedEventArgs
  Microsoft.Xna.Framework.Net.NetworkException
  Microsoft.Xna.Framework.Net.NetworkNotAvailableException
  Microsoft.Xna.Framework.NoSuitableGraphicsDeviceException
  Microsoft.Xna.Framework.PowerLineStatus
  Microsoft.Xna.Framework.PowerStatus
  System.ApplicationException
  System.CharEnumerator
  System.Collections.ArrayList
  System.Collections.CaseInsensitiveComparer
  System.Collections.CaseInsensitiveHashCodeProvider
  System.Collections.CollectionBase
  System.Collections.Comparer
  System.Collections.Generic.SortedList`2
  System.Collections.Hashtable
  System.Collections.IHashCodeProvider
  System.Collections.Queue
  System.Collections.SortedList
  System.Collections.Specialized.BitVector32
  System.Collections.Specialized.BitVector32/Section
  System.Collections.Specialized.HybridDictionary
  System.Collections.Specialized.ListDictionary
  System.Collections.Specialized.NameObjectCollectionBase
  System.Collections.Specialized.NameObjectCollectionBase/KeysCollection
  System.Collections.Specialized.NameValueCollection
  System.Collections.Specialized.StringDictionary
  System.Collections.Stack
  System.ComponentModel.AddingNewEventArgs
  System.ComponentModel.AddingNewEventHandler
  System.ComponentModel.AttributeCollection
  System.ComponentModel.BindingList`1
  System.ComponentModel.CancelEventHandler
  System.ComponentModel.CollectionChangeAction
  System.ComponentModel.CollectionChangeEventArgs
  System.ComponentModel.CollectionChangeEventHandler
  System.ComponentModel.Component
  System.ComponentModel.ComponentResourceManager
  System.ComponentModel.Container
  System.ComponentModel.DataObjectAttribute
  System.ComponentModel.DataObjectMethodAttribute
  System.ComponentModel.DataObjectMethodType
  System.ComponentModel.DesignerCategoryAttribute
  System.ComponentModel.DesignTimeVisibleAttribute
  System.ComponentModel.EventDescriptor
  System.ComponentModel.EventDescriptorCollection
  System.ComponentModel.EventHandlerList
  System.ComponentModel.IBindingList
  System.ComponentModel.IBindingListView
  System.ComponentModel.ICancelAddNew
  System.ComponentModel.ICustomTypeDescriptor
  System.ComponentModel.IDataErrorInfo
  System.ComponentModel.IListSource
  System.ComponentModel.IRaiseItemChangedEvents
  System.ComponentModel.ISupportInitialize
  System.ComponentModel.ISupportInitializeNotification
  System.ComponentModel.ITypedList
  System.ComponentModel.ListChangedEventArgs
  System.ComponentModel.ListChangedEventHandler
  System.ComponentModel.ListChangedType
  System.ComponentModel.ListSortDescription
  System.ComponentModel.ListSortDescriptionCollection
  System.ComponentModel.MarshalByValueComponent
  System.ComponentModel.MemberDescriptor
  System.ComponentModel.PropertyDescriptorCollection
  System.ComponentModel.TypeDescriptor
  System.ComponentModel.Win32Exception
  System.Diagnostics.DefaultTraceListener
  System.Diagnostics.TextWriterTraceListener
  System.Diagnostics.Trace
  System.Diagnostics.TraceListener
  System.Diagnostics.TraceListenerCollection
  System.Globalization.CultureTypes
  System.Globalization.DaylightTime
  System.IO.Compression.CompressionMode
  System.IO.Compression.DeflateStream
  System.IO.Compression.GZipStream
  System.IO.InvalidDataException
  System.MarshalByRefObject
  System.Resources.ResourceReader
  System.Security.Policy.Evidence
  System.SerializableAttribute
  System.Text.ASCIIEncoding
  System.Text.RegularExpressions.RegexRunner
  System.Text.RegularExpressions.RegexRunnerFactory
  System.Text.UTF7Encoding
  System.Threading.EventResetMode
  System.Threading.Mutex
  System.Threading.ThreadPriority
  System.TimeZone
  System.TypedReference
  System.UriHostNameType
  System.UriPartial
  System.Xml.EntityHandling
  System.Xml.Formatting
  System.Xml.IHasXmlNode
  System.Xml.Schema.IXmlSchemaInfo
  System.Xml.Schema.ValidationEventArgs
  System.Xml.Schema.ValidationEventHandler
  System.Xml.Schema.XmlAtomicValue
  System.Xml.Schema.XmlSchemaAll
  System.Xml.Schema.XmlSchemaAnnotated
  System.Xml.Schema.XmlSchemaAnnotation
  System.Xml.Schema.XmlSchemaAny
  System.Xml.Schema.XmlSchemaAnyAttribute
  System.Xml.Schema.XmlSchemaAppInfo
  System.Xml.Schema.XmlSchemaAttribute
  System.Xml.Schema.XmlSchemaAttributeGroup
  System.Xml.Schema.XmlSchemaAttributeGroupRef
  System.Xml.Schema.XmlSchemaChoice
  System.Xml.Schema.XmlSchemaCompilationSettings
  System.Xml.Schema.XmlSchemaComplexContent
  System.Xml.Schema.XmlSchemaComplexContentExtension
  System.Xml.Schema.XmlSchemaComplexContentRestriction
  System.Xml.Schema.XmlSchemaComplexType
  System.Xml.Schema.XmlSchemaContent
  System.Xml.Schema.XmlSchemaContentModel
  System.Xml.Schema.XmlSchemaContentProcessing
  System.Xml.Schema.XmlSchemaContentType
  System.Xml.Schema.XmlSchemaDatatype
  System.Xml.Schema.XmlSchemaDatatypeVariety
  System.Xml.Schema.XmlSchemaDerivationMethod
  System.Xml.Schema.XmlSchemaDocumentation
  System.Xml.Schema.XmlSchemaElement
  System.Xml.Schema.XmlSchemaEnumerationFacet
  System.Xml.Schema.XmlSchemaException
  System.Xml.Schema.XmlSchemaExternal
  System.Xml.Schema.XmlSchemaFacet
  System.Xml.Schema.XmlSchemaFractionDigitsFacet
  System.Xml.Schema.XmlSchemaGroup
  System.Xml.Schema.XmlSchemaGroupBase
  System.Xml.Schema.XmlSchemaGroupRef
  System.Xml.Schema.XmlSchemaIdentityConstraint
  System.Xml.Schema.XmlSchemaImport
  System.Xml.Schema.XmlSchemaInclude
  System.Xml.Schema.XmlSchemaInference
  System.Xml.Schema.XmlSchemaInference/InferenceOption
  System.Xml.Schema.XmlSchemaInferenceException
  System.Xml.Schema.XmlSchemaInfo
  System.Xml.Schema.XmlSchemaKey
  System.Xml.Schema.XmlSchemaKeyref
  System.Xml.Schema.XmlSchemaLengthFacet
  System.Xml.Schema.XmlSchemaMaxExclusiveFacet
  System.Xml.Schema.XmlSchemaMaxInclusiveFacet
  System.Xml.Schema.XmlSchemaMaxLengthFacet
  System.Xml.Schema.XmlSchemaMinExclusiveFacet
  System.Xml.Schema.XmlSchemaMinInclusiveFacet
  System.Xml.Schema.XmlSchemaMinLengthFacet
  System.Xml.Schema.XmlSchemaNotation
  System.Xml.Schema.XmlSchemaNumericFacet
  System.Xml.Schema.XmlSchemaObjectCollection
  System.Xml.Schema.XmlSchemaObjectEnumerator
  System.Xml.Schema.XmlSchemaObjectTable
  System.Xml.Schema.XmlSchemaParticle
  System.Xml.Schema.XmlSchemaPatternFacet
  System.Xml.Schema.XmlSchemaRedefine
  System.Xml.Schema.XmlSchemaSequence
  System.Xml.Schema.XmlSchemaSimpleContent
  System.Xml.Schema.XmlSchemaSimpleContentExtension
  System.Xml.Schema.XmlSchemaSimpleContentRestriction
  System.Xml.Schema.XmlSchemaSimpleType
  System.Xml.Schema.XmlSchemaSimpleTypeContent
  System.Xml.Schema.XmlSchemaSimpleTypeList
  System.Xml.Schema.XmlSchemaSimpleTypeRestriction
  System.Xml.Schema.XmlSchemaSimpleTypeUnion
  System.Xml.Schema.XmlSchemaTotalDigitsFacet
  System.Xml.Schema.XmlSchemaType
  System.Xml.Schema.XmlSchemaUnique
  System.Xml.Schema.XmlSchemaUse
  System.Xml.Schema.XmlSchemaValidationException
  System.Xml.Schema.XmlSchemaValidationFlags
  System.Xml.Schema.XmlSchemaValidator
  System.Xml.Schema.XmlSchemaValidity
  System.Xml.Schema.XmlSchemaWhiteSpaceFacet
  System.Xml.Schema.XmlSchemaXPath
  System.Xml.Schema.XmlValueGetter
  System.Xml.Serialization.IXmlTextParser
  System.Xml.Serialization.SoapAttributeAttribute
  System.Xml.Serialization.SoapAttributeOverrides
  System.Xml.Serialization.SoapAttributes
  System.Xml.Serialization.SoapElementAttribute
  System.Xml.Serialization.SoapEnumAttribute
  System.Xml.Serialization.SoapIgnoreAttribute
  System.Xml.Serialization.SoapIncludeAttribute
  System.Xml.Serialization.SoapReflectionImporter
  System.Xml.Serialization.SoapTypeAttribute
  System.Xml.Serialization.UnreferencedObjectEventArgs
  System.Xml.Serialization.UnreferencedObjectEventHandler
  System.Xml.Serialization.XmlAnyAttributeAttribute
  System.Xml.Serialization.XmlAttributeEventArgs
  System.Xml.Serialization.XmlAttributeEventHandler
  System.Xml.Serialization.XmlElementEventArgs
  System.Xml.Serialization.XmlElementEventHandler
  System.Xml.Serialization.XmlNodeEventArgs
  System.Xml.Serialization.XmlNodeEventHandler
  System.Xml.ValidationType
  System.Xml.WhitespaceHandling
  System.Xml.XmlAttribute
  System.Xml.XmlAttributeCollection
  System.Xml.XmlCDataSection
  System.Xml.XmlCharacterData
  System.Xml.XmlComment
  System.Xml.XmlDeclaration
  System.Xml.XmlDocument
  System.Xml.XmlDocumentFragment
  System.Xml.XmlElement
  System.Xml.XmlEntityReference
  System.Xml.XmlImplementation
  System.Xml.XmlLinkedNode
  System.Xml.XmlNamedNodeMap
  System.Xml.XmlNode
  System.Xml.XmlNodeChangedAction
  System.Xml.XmlNodeChangedEventArgs
  System.Xml.XmlNodeChangedEventHandler
  System.Xml.XmlNodeList
  System.Xml.XmlNodeOrder
  System.Xml.XmlNodeReader
  System.Xml.XmlOutputMethod
  System.Xml.XmlProcessingInstruction
  System.Xml.XmlSignificantWhitespace
  System.Xml.XmlText
  System.Xml.XmlTextReader
  System.Xml.XmlTextWriter
  System.Xml.XmlUrlResolver
  System.Xml.XmlWhitespace
  System.Xml.XPath.XPathException
  System.Xml.XPath.XPathItem
  System.Xml.Xsl.XsltException
</pre>
<h3>System types <strong>added</strong> to the Xbox 360 Compact Framework</h3>
<p>These are types which did <strong>not</strong> exist in the Compact Framework for the Xbox 360, in the &#8220;XNA Game Studio&#8221; v3.1 release. But these are now present in the new v4.0 release:</p>
<pre>
  Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid
  Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
  Microsoft.Win32.SafeHandles.SafeWaitHandle
  Microsoft.Xna.Framework.Audio.AudioChannels
  Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance
  Microsoft.Xna.Framework.Audio.Microphone
  Microsoft.Xna.Framework.Audio.MicrophoneState
  Microsoft.Xna.Framework.Audio.NoMicrophoneConnectedException
  Microsoft.Xna.Framework.Color
  Microsoft.Xna.Framework.DisplayOrientation
  Microsoft.Xna.Framework.GamerServices.Achievement
  Microsoft.Xna.Framework.GamerServices.AchievementCollection
  Microsoft.Xna.Framework.GamerServices.AvatarRendererState
  Microsoft.Xna.Framework.GamerServices.GameUpdateRequiredException
  Microsoft.Xna.Framework.GamerServices.IAvatarAnimation
  Microsoft.Xna.Framework.GamerServices.InviteAcceptedEventArgs
  Microsoft.Xna.Framework.GamerServices.LeaderboardEntry
  Microsoft.Xna.Framework.GamerServices.LeaderboardIdentity
  Microsoft.Xna.Framework.GamerServices.LeaderboardKey
  Microsoft.Xna.Framework.GamerServices.LeaderboardOutcome
  Microsoft.Xna.Framework.GamerServices.LeaderboardReader
  Microsoft.Xna.Framework.GamerServices.LeaderboardWriter
  Microsoft.Xna.Framework.GamerServices.NetworkException
  Microsoft.Xna.Framework.GamerServices.NetworkNotAvailableException
  Microsoft.Xna.Framework.GamerServices.PropertyDictionary
  Microsoft.Xna.Framework.Graphics.AlphaTestEffect
  Microsoft.Xna.Framework.Graphics.BlendState
  Microsoft.Xna.Framework.Graphics.DepthStencilState
  Microsoft.Xna.Framework.Graphics.DirectionalLight
  Microsoft.Xna.Framework.Graphics.DualTextureEffect
  Microsoft.Xna.Framework.Graphics.EffectMaterial
  Microsoft.Xna.Framework.Graphics.EnvironmentMapEffect
  Microsoft.Xna.Framework.Graphics.GraphicsProfile
  Microsoft.Xna.Framework.Graphics.IEffectFog
  Microsoft.Xna.Framework.Graphics.IEffectLights
  Microsoft.Xna.Framework.Graphics.IEffectMatrices
  Microsoft.Xna.Framework.Graphics.IVertexType
  Microsoft.Xna.Framework.Graphics.NoSuitableGraphicsDeviceException
  Microsoft.Xna.Framework.Graphics.PackedVector.Bgra4444
  Microsoft.Xna.Framework.Graphics.RasterizerState
  Microsoft.Xna.Framework.Graphics.RenderTargetBinding
  Microsoft.Xna.Framework.Graphics.SkinnedEffect
  Microsoft.Xna.Framework.Graphics.VertexBufferBinding
  Microsoft.Xna.Framework.LaunchParameters
  Microsoft.Xna.Framework.Net.WriteLeaderboardsEventArgs
  Microsoft.Xna.Framework.TitleContainer
  System.AccessViolationException
  System.AppDomainManager
  System.AppDomainSetup
  System.ComponentModel.AsyncOperation
  System.ComponentModel.AsyncOperationManager
  System.ComponentModel.BackgroundWorker
  System.ComponentModel.CategoryAttribute
  System.ComponentModel.ComponentCollection
  System.ComponentModel.DescriptionAttribute
  System.ComponentModel.DoWorkEventArgs
  System.ComponentModel.DoWorkEventHandler
  System.ComponentModel.ITypeDescriptorContext
  System.ComponentModel.ProgressChangedEventArgs
  System.ComponentModel.ProgressChangedEventHandler
  System.ComponentModel.ReadOnlyAttribute
  System.ComponentModel.RunWorkerCompletedEventArgs
  System.ComponentModel.RunWorkerCompletedEventHandler
  System.ComponentModel.TypeConverterAttribute
  System.ContextStaticAttribute
  System.DataMisalignedException
  System.DateTimeOffset
  System.Diagnostics.DebuggerBrowsableAttribute
  System.Diagnostics.DebuggerBrowsableState
  System.Diagnostics.DebuggerDisplayAttribute
  System.Diagnostics.DebuggerTypeProxyAttribute
  System.Diagnostics.StackFrame
  System.Diagnostics.StackTrace
  System.DllNotFoundException
  System.Environment/SpecialFolder
  System.ExecutionEngineException
  System.FieldAccessException
  System.FileStyleUriParser
  System.FtpStyleUriParser
  System.GenericUriParser
  System.GenericUriParserOptions
  System.Globalization.HebrewCalendar
  System.Globalization.HijriCalendar
  System.Globalization.UmAlQuraCalendar
  System.HttpStyleUriParser
  System.InvalidTimeZoneException
  System.IO.FileLoadException
  System.IO.IsolatedStorage.IsolatedStorageException
  System.IO.IsolatedStorage.IsolatedStorageFile
  System.IO.IsolatedStorage.IsolatedStorageFileStream
  System.IO.UnmanagedMemoryStream
  System.LoaderOptimization
  System.MissingFieldException
  System.NotFiniteNumberException
  System.Reflection.AssemblyFileVersionAttribute
  System.Reflection.GenericParameterAttributes
  System.Reflection.InterfaceMapping
  System.Reflection.IReflect
  System.Reflection.LocalVariableInfo
  System.Reflection.MemberFilter
  System.Reflection.ReflectionTypeLoadException
  System.Reflection.ResourceAttributes
  System.Reflection.TargetException
  System.Reflection.TypeDelegator
  System.ResolveEventArgs
  System.ResolveEventHandler
  System.Resources.UltimateResourceFallbackLocation
  System.Runtime.CompilerServices.CompilationRelaxations
  System.Runtime.CompilerServices.CompilationRelaxationsAttribute
  System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
  System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute
  System.Runtime.InteropServices.ClassInterfaceAttribute
  System.Runtime.InteropServices.ClassInterfaceType
  System.Runtime.InteropServices.CoClassAttribute
  System.Runtime.InteropServices.ComDefaultInterfaceAttribute
  System.Runtime.InteropServices.COMException
  System.Runtime.InteropServices.ComImportAttribute
  System.Runtime.InteropServices.ComInterfaceType
  System.Runtime.InteropServices.DispIdAttribute
  System.Runtime.InteropServices.InterfaceTypeAttribute
  System.Runtime.InteropServices.SafeHandle
  System.Runtime.Serialization.OnDeserializedAttribute
  System.Runtime.Serialization.OnDeserializingAttribute
  System.Runtime.Serialization.OnSerializedAttribute
  System.Runtime.Serialization.OnSerializingAttribute
  System.Runtime.Serialization.StreamingContext
  System.Runtime.Serialization.StreamingContextStates
  System.Runtime.Versioning.TargetFrameworkAttribute
  System.RuntimeArgumentHandle
  System.Security.Permissions.CodeAccessSecurityAttribute
  System.Security.Permissions.SecurityAttribute
  System.Security.Permissions.SecurityPermissionAttribute
  System.Security.Permissions.SecurityPermissionFlag
  System.Security.Principal.IIdentity
  System.Security.Principal.IPrincipal
  System.Security.SecurityCriticalAttribute
  System.Security.SecuritySafeCriticalAttribute
  System.Security.SecurityState
  System.Security.SecurityTransparentAttribute
  System.Security.UnverifiableCodeAttribute
  System.ServiceModel.XmlSerializerFormatAttribute
  System.StringSplitOptions
  System.Text.DecoderFallbackException
  System.Text.EncoderFallbackException
  System.Threading.IOCompletionCallback
  System.Threading.NativeOverlapped
  System.Threading.Overlapped
  System.Threading.ParameterizedThreadStart
  System.Threading.RegisteredWaitHandle
  System.Threading.SendOrPostCallback
  System.Threading.SynchronizationContext
  System.Threading.SynchronizationLockException
  System.Threading.ThreadStartException
  System.Threading.ThreadState
  System.Threading.WaitOrTimerCallback
  System.ThreadStaticAttribute
  System.TimeZoneInfo
  System.TypeInitializationException
  System.UriBuilder
  System.UriIdnScope
  System.UriParser
  System.UriTypeConverter
  System.Xml.DtdProcessing
  System.Xml.Linq.ReaderOptions
  System.Xml.NamespaceHandling
  System.Xml.Serialization.XmlMappingAccess
</pre>
<h3>Notables?</h3>
<p>A number of deprecated collections are no longer available, the classic &#8220;ArrayList&#8221; from C# 1.0 among several others. Most of these would cause big performance problems with the Xbox garbage collector, so makes total sense that they have been trimmed out.</p>
<p>Additions which piqued my interest included <strong>&#8220;DebuggerDisplayAttribute&#8221;</strong>, and <strong>&#8220;StackTrace&#8221;/ &#8220;StackFrame&#8221;</strong>. The former I have a vague recollection trying to use before, it helps <a href="http://msdn.microsoft.com/en-us/library/x810d419.aspx" target="_blank">nicely format how a type is viewed in the Debugger</a>. You can achieve the same functionality with ToString(), but if you need to use ToString() for runtime purposes and want something different shown in the debugger, it&#8217;s useful. &#8220;StackTrace&#8221; I was interested in because I believe the crash handler I&#8217;d written had a slightly different pathway between 360 and Windows. For 360 I had to throw an exception, and handle it. In the exception handling code I could pull out the callstack. With the StackTrace class you can just grab the callstack right off in the crash handler.</p>
<p><strong>&#8220;System.Threading.ThreadState&#8221;</strong> too, I think I&#8217;d had to do a different workaround for the Xbox in the past. Nice to see that it&#8217;s now available. </p>
<p>Strangely I noticed <strong>&#8220;System.LocalDataStoreSlot&#8221;</strong> is not included in my removal list. Not sure why this is the case. Maybe I missed some key parameter in &#8216;ildasm&#8217;?</p>
<h3>The Zune, or Windows 7 Phone?</h3>
<p>Sorry, but I haven&#8217;t been developing for those platforms. Given some comments about the v4.0 release wanting to &#8216;standardize&#8217; the Compact Framework to some kind of &#8220;Silverlight&#8221; API-set, I&#8217;d imagine the ones I&#8217;ve mentioned were added will probably exist for these platforms too. No idea though whether all the removed types I list apply to the Zune, many may not have even existed in the first place.</p>
<p>Er&#8230; So yeah, this is just covering the Xbox. Your mileage may vary with the other platforms.</p>
<p><b>Edit: Ah, Zune <a href="http://news.softpedia.com/news/XNA-Game-Studio-4-0-Not-for-Zune-HD-Just-Windows-Xbox-360-and-Windows-Phone-7-136999.shtml" target="_blank">isn&#8217;t even supported</a> by XNA 4.0!</b></p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/2weec7k5.aspx" target="_blank">MSDN: Differences Between the .NET Compact Framework and the .NET Framework</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb203915.aspx" target="_blank">MSDN: Namespaces, Types, and Members in the .NET Compact Framework for Xbox 360</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/60727/373621.aspx" target="_blank">Forums: XNA 4.0 RTM &#8211; Xbox Project &#8211; Serializable doesnt work</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/62420/383733.aspx" target="_blank">Forums: XNA 4.0 .Net reference version for XBox</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/66363/406010.aspx" target="_blank">Forums: Thread.Priority property deprecated on 360/XNA 4.0?</a></li>
<li><a href="http://blogs.msdn.com/b/shawnhar/archive/2010/03/16/breaking-changes-in-xna-game-studio-4-0.aspx?PageIndex=3" target="_blank">Shawn&#8217;s Blog: Breaking changes in XNA Game Studio 4.0</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNACPC &#8211; An Amstrad CPC Emulator for the Xbox 360</title>
		<link>http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/#comments</comments>
		<pubDate>Fri, 21 May 2010 17:17:58 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[amstrad]]></category>
		<category><![CDATA[amstrad cpc]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=621</guid>
		<description><![CDATA[A few weeks ago I mentioned on twitter that I was working on an Amstrad CPC emulator, written in XNA. There are plenty of the things for the PC and various other consoles, but not one for the Xbox 360 yet. So it seemed a cool little exercise to undertake. A long time ago, I [...]]]></description>
			<content:encoded><![CDATA[<p align=center><img src="http://www.gavpugh.com/wp-content/uploads/2010/05/cpcemulator1.jpg" alt="" title="CPC464" width="529" height="322" class="aligncenter size-full wp-image-630" /></p>
<p>A few weeks ago I mentioned on <a href="http://twitter.com/gavin_pugh" target="_new">twitter</a> that I was working on an <a href="http://en.wikipedia.org/wiki/Amstrad_CPC" target="_new">Amstrad CPC</a> emulator, written in XNA. There are plenty of the things for the PC and various other consoles, but not one for the Xbox 360 yet. So it seemed a cool little exercise to undertake.</p>
<p>A long time ago, I wrote one of my own for the PC. The website I setup for it is still live, <a href="http://www.angelfire.com/retro2/cpc3d/" target="_new">here</a>. I developed it initially around 1997. Back then I’d pretty much just gotten it to be able to boot, and be able to type things on the keyboard. I revisited it a few years later when I needed something flashy for my portfolio, around the time I was trying to break into the games industry. With that version I managed to get a handful of games running nicely.</p>
<p><span id="more-621"></span></p>
<h3>Little bit of history</h3>
<p>I used to be really into the emulation scene back in the day. The first one I stumbled upon was on a <a href="http://en.wikipedia.org/wiki/Bulletin_board_system" target="_new">BBS</a>, some random BBS I found in the pages of <a href="http://www.computershopper.co.uk/" target="_new">Computer Shopper</a> (wow, that mag is still going!). My father used to go to his work to wash his car on the odd weekend here and there. I used to use his Apple Mac computer when he was doing that, was one of the old Mac Quadras. This would have been around 1993 I think, so I’d have been a spritely twelve or thirteen years old at the time!</p>
<p>Anyhow, I’d use some terminal software on the Mac, downloading various interesting programming bits and bobs via the trusty <a href="http://en.wikipedia.org/wiki/ZMODEM" target="_new">ZMODEM</a> protocol. One weekend I was stunned to see something called CPCEMU. This was the first Amstrad emulator ever to see the light of day. I didn’t even know such a thing was possible at the time; I’d pretty much figured that it could well be a joke download. So after copying my weekend’s haul to a floppy as per-usual, I was excited to give it a try.</p>
<p>This software and much of the rest of the stuff I downloaded was PC-only. I didn’t have a PC at home at the time; I’d just use the ones at my school during lunchtimes. It was really cool to see the emulator fire up on that PC at school. Unfortunately though the Amstrad ROM wasn’t included in the package, so all that worked out of the box was a single sample game written to interface directly with the hardware. That year I remember my ‘big’ Christmas present was a 3.5” disc drive for the Amstrad, primarily so I could dump the ROMs from the machine so I could get the emulator working! What a nerd. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Around the time I’d also written in to the only remaining Amstrad CPC magazine in production: Amstrad Action. They had some feature where they asked readers to write in with any sort of Amstrad-related article, and they’d print them up in some sort of ‘readers articles’ feature. This never actually happened though unfortunately; they never did run any reader articles. I’d written one in about CPCEMU, whilst it never appeared I did get a mention in the magazine. After a little googling, I managed to find it:</p>
<div align=center><b><i><br />
<a href="http://www.gavpugh.com/wp-content/uploads/2010/05/aa104-081.jpg"><img src="http://www.gavpugh.com/wp-content/uploads/2010/05/aa104-08-212x300.jpg" alt="" title="aa104-08" width="212" height="300" class="size-medium wp-image-632" /></a> <br />Amstrad Action – #104 – May 1994 (click for larger image)<br /></b></i></div>
<p>&nbsp;</p>
<p>Brought a smile to my face seeing it after all these years!</p>
<h3>Other emulators</h3>
<p>There were a number of other emulators I ‘followed’ back in the day too. <a href="http://www.zophar.net/genesis/genem.html" target="_new">GenEm</a>; the first SEGA Genesis / Megadrive emulator out there, was one in particular. Was really something to see it improve over time. From humble beginnings where only a handful of early-era games are only playable. Through to audio emulation working (the Genesis/MD has a second processor; a Z80 funnily enough, which is primarily used for audio in games). Around this time was an explosion in emulators in general, for all sorts of other videogame systems of similar eras. There was a bit of a race between coders to get their emulator to be the most fully featured, with the highest game-compatibility rate. Competition drives technology, I guess?</p>
<p>Some other ones I remember too were <a href="http://www.zophar.net/genesis/kgen.html" target="_new">KGEN</a> and <a href="http://www.zophar.net/genesis.html" target="_new">DGEN</a>. But the real leap at the time I recall was <a href="http://bloodlust.zophar.net/gen/genecyst.html" target="_new">Genecyst</a>. It was really leaps and bounds above the other ones out at the time. The same guy (or group) that coded it also wrote the impressive <a href="http://bloodlust.zophar.net/Callus/callus.html" target="_new">Callus</a>, and <a href="http://bloodlust.zophar.net/NESticle/nes.html" target="_new">NESticle</a>. Both landmarks at the time, particularly Callus which I think was the first Capcom arcade emulator that ran at a playable speed.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/05/Genecyst1.jpg" alt="" title="Genecyst" width="250" height="219" class="alignnone size-full wp-image-644" /><br />The UI for Genecyst, all emulators for the era were in DOS. Unlike most, this one had a GUI too<br /></b></i></div>
<p>&nbsp;</p>
<p>I also remember <a href="http://en.wikipedia.org/wiki/Executor_%28software%29" target="_new">Executor</a> well too, an Apple Mac emulator. This one took an interesting approach of not making use of any System ROMs at all. They essentially reverse-engineered the Mac. The emulation effectively emulated the services/OS calls that the system ROM would have provided. This I think was more of a legal choice than a practical one, but it must have been an interesting technical challenge. They updated it pretty often, it seemed like every week there was a new one to try that had a new slate of improvements. Unfortunately it was a paid-for emulator. I think it had a time restriction on it, it worked for ten minutes and then quit out. That was a rarity back then in the emulator scene.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/05/Executor_emu1.jpg" alt="" title="Executor_emu" width="350" height="274" class="alignnone size-full wp-image-647" /><br />Screenshot of Executor in action<br /></b></i></div>
<p>&nbsp;</p>
<p>As I was looking for stuff for this article, I was surprised to see that it’s now open-source. I think now there’s probably several other Mac emulators which take the more traditional approach, and have a near 100% compatibility with a real 68k-era Mac. I wonder how well it sold throughout its lifetime?</p>
<h3>An XNA CPC Emulator</h3>
<p>Christ; I do go on like an old woman, don’t I? <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The point of this article was meant to be about the Xbox 360 version of the emulator I’m working on. I did most of the work for it over a weekend, about a month ago. The missus was away for work, and I had a nice block of time to tackle it. I essentially just used my previous emulator I wrote a few years prior, in plain C. I rewrote it in C#, in a much more OO-way.</p>
<p>It was as a pretty straightforward process. As I’d done with my older emulator, I took the Z80 CPU emulation from an existing source. Someone has already coded a ZX Spectrum emulator in C#, so I took the CPU code from there. The <a href="http://zx360.codeplex.com/" target="_new">Zx360 project</a>. I had to make a few modifications though. One was based on how memory is accessed on the CPC, to handle the ROM and RAM banking. The other was for the way interrupts are handled. I know very little about the Spectrum, but it seems like they do behave pretty differently in that regard.</p>
<p>So, dusting off the cobwebby corners of my mind, I got to implementing all the various bits of hardware of the machine. Using both my old source, and the <a href="http://cpctech.cpc-live.com/" target="_new">Unofficial Amstrad WWW Resource</a> for reference. The code quality was like night and day compared to my old plain-C implementation. That’s I guess what thirteen years experience will help you out a bit with! It a joy to debug too; all the little components of the machine browsable in the Visual Studio debugger, in a nice OO-d tree!</p>
<p>I worked on the actual XNA-specific parts last. Getting the screen drawn, and getting input working that is. It’s just as cool as I remember when you get that startup screen rendering the very first time. This old thing:</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/05/boot1.jpg" alt="" title="XNACPC Boot" width="500" height="375" class="alignnone size-full wp-image-649" /><br />XNACPC bootup, the Amstrad CPC 464 startup screen<br /></b></i></div>
<p>&nbsp;</p>
<p> I then went on to get snapshot (.SNA) support working so I could load up memory snapshots of games. That was awesome to see as well. It had the exact same level of compatibility as my older emulator. I was a little worried the new Z80 core code could have some bugs or issues, but it seems solid now. So anyway, the same games that ran fine worked fine on this too. But of course the same ones with issues, also had issues on my new emulator too. Once I’d played a few games on the Xbox itself, I took a break from the project for a while.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/05/rointime1.jpg" alt="" title="XNACPC Roland In Time" width="500" height="375" class="alignnone size-full wp-image-651" /><br />The classic ‘Roland in Time’ running on XNACPC, on an Xbox 360<br /></b></i></div>
<p>&nbsp;</p>
<h3>A bit later on</h3>
<p>What I really wanted to add was proper audio support. I dabbled for a while using XACT; playing a sound and messing with the pitch and volume of it. But it had pretty hideous results. It was encouraging to hear the tunes in there somewhere, but it really didn’t work well at all. What led me to stop bothering with this method was news that XNA 4.0 has nicer audio support. Specifically the class <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.dynamicsoundeffectinstance%28XNAGameStudio.40%29.aspx" target="_new">DynamicSoundEffectInstance</a>. This class allows playback of raw audio data, not just samples. Exactly what an emulator needs.</p>
<p>The other avenue I wanted to make improvements on was to how I emulate the video hardware. My older emulator took a very naïve approach. It didn’t make any effort to emulate vsync, hsync or tie in the CPU interrupts with any of it. Over the past few weeks I’ve had some time here and there to mess with this stuff, and attempt to get something better working. I’m pretty pleased with the results. I managed to get split-screen working. Which means ‘Sorcery’, one of the classic CPC titles is now fully playable and looks just like the original.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/05/sorcery1.jpg" alt="" title="XNACPC Sorcery" width="500" height="375" class="alignnone size-full wp-image-652" /><br />Sorcery on XNACPC &#8211; A CRTC-splitscreen game<br /></b></i></div>
<p>&nbsp;</p>
<p>I’ve still a way to go though. My CRTC and video emulation isn’t quite up to par with some of the more accomplished emulators already out on PC. Well, that’s an understatement; it’s truly awful compared to most of those emulators! But it’s something I can improve at my leisure. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I plan to release the source code for the emulator, specifically once I’ve got my video code a little more stable. Whether that’s a matter of weeks or months, I don’t know. I’m pretty busy at the moment with <a href="http://www.neversoft.com" target="_new">work</a>, so it may take a fair while. I’d probably expect it to be after XNA 4.0 is released too, since I’d probably get some crude level of audio support in once it’s out. I’d dabble with the <a href="http://creators.xna.com/en-US/downloads" target="_new">CTP version</a> that’s out now, but I’m really targeting Xbox which is not supported just yet. Yes, I could write the code on PC. But I really like firing up the emulator on the Xbox, and seeing the cool stuff running on there first. I can be patient&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Thread.CurrentThread is slow on Xbox 360</title>
		<link>http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 17:01:46 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CurrentThread]]></category>
		<category><![CDATA[CurrentThreadLite]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[Thread.CurrentThread]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=538</guid>
		<description><![CDATA[I’ve still a few more XNA articles I’ve been planning to write. The next one was to involve some threading code, and in the process of creating the article I hit upon something that I found concerning. The title of this article pretty much gives it away before I can casually introduce it; the property [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-283  aligncenter" title="ThreadStatic XNA" src="http://www.gavpugh.com/wp-content/uploads/2010/03/threadpic1.jpg" alt="ThreadStatic XNA" width="250" height="250" /></p>
<p>I’ve still a few more XNA articles I’ve been planning to write. The next one was to involve some threading code, and in the process of creating the article I hit upon something that I found concerning.</p>
<p>The title of this article pretty much gives it away before I can casually introduce it; the property method <strong>Thread.CurrentThread</strong> is slow on the Xbox. Specifically it’s slow compared to running the same code on a Windows PC. I’d imagine the same applies to the other Compact Framework platforms too; the Zune and Windows 7 Phones. But I can’t say for sure.<br />
<span id="more-538"></span></p>
<h3>Bone-headed code</h3>
<p>I stumbled upon this whilst trying to profile some of my code for a future threading article. I had two different techniques I was comparing, and I couldn’t for the life of me understand why one was an order of magnitude slower than the other. It just didn’t make any sense.</p>
<p>What I’d done in one of them was to assume that <strong>Thread.CurrentThread</strong> is cheap, and simply returns some kind of easy to grab variable. This isn’t the case. I can illustrate by showing you the exact piece of code that was slow:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> MAX_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> m_data<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_id</span> <span style="color: #008000;">==</span> Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentThread</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> m_data<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">m_data</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Then I changed my slower technique to ‘match’ the faster one, by prefetching the current thread:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread thread_id <span style="color: #008000;">=</span> Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> MAX_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> m_data<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_id</span> <span style="color: #008000;">==</span> thread_id <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> m_data<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">m_data</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Yes, seems a no-brainer doesn’t it? In most cases it does make sense to prefetch variables like that, but I’d been a little silly and assumed there would be negligible difference from not doing so. I’d had some harebrained ideal that the optimizing compiler and the JIT-er would effectively make these two bits of code the same. On my Windows PC build they actually do execute in almost the same amount of time, certainly not different to the same degree as on Xbox.</p>
<p>It makes total sense that it doesn’t get optimized on either platform though. If you look at <strong>Thread.CurrentThread </strong>in the <a href="http://www.red-gate.com/products/reflector/" target="_new">.NET Reflector</a>, it calls an external DLL function. The compiler (or JIT-er) can’t be expected to think that the return value of that function will be the same for each iteration of the loop.</p>
<h3>So, how slow is it?</h3>
<p>My first port of call after I realized the big timesink, was to directly compare the performance between the Windows PC build and the Xbox 360 build. My test code was as follows, a loop accessing Thread.CurrentThread a million times:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread thread <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000000</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    thread <span style="color: #008000;">=</span> Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Here’s how long it took on each platform:</p>
<table>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Windows PC Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>0.0088s
</td>
</tr>
<tr height=15px>
<td width=100px></td>
<td width=300px></td>
<td>
</td>
</tr>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Xbox 360 Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>4.95s
</td>
</tr>
</table>
<p>&nbsp;</p>
<p>Calling Thread.CurrentThread on the Xbox 360 is over five hundred (500!) times slower than on PC. That’s not good! The PC I’m using is nothing special, it’s a three year old Core Duo ‘1’ laptop. So I’m not running some ridiculous PC rig to see these large differences in speeds.</p>
<p>For the code I was working on, I modified it to call Thread.CurrentThread once at the start of my worker thread. I then pass this Thread object through to the other methods that I used, which are called often within that worker thread. So where these methods used to call CurrentThread multiple times themselves before, they no longer needed to. The Thread object for this worker thread was simply passed around instead. The code doesn’t look quite as nice of course, but it’s hardly a disaster.</p>
<p>The particular test I was doing with that worker thread code ran over one hundred times faster with that change made. This was still a bit of a micro-benchmark though, calling some small pieces of code a ridiculous number of times… Regardless, I was just trying to battle-test something that I’d want to use in practice. Using Thread.CurrentThread was an integral part of that.</p>
<p>What I ended up doing was having the facility to optionally pass in a Thread object if the user has one. If they didn’t, it would end up resorting to the slow Thread.CurrentThread instead. This seemed like an ideal solution.</p>
<h3>CurrentThreadLite</h3>
<p>When looking at the CurrentThread property accessor in <a href="http://www.red-gate.com/products/reflector/" target="_new">.NET Reflector</a>, I traced through to the DLL function which is ultimately called:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> Thread CurrentThread
<span style="color: #008000;">&#123;</span>
    get
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">return</span> PAL<span style="color: #008000;">.</span><span style="color: #0000FF;">Threading_Thread_CurrentThread</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;mscoree&quot;</span>, EntryPoint<span style="color: #008000;">=</span><span style="color: #666666;">&quot;#210&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> Thread Threading_Thread_CurrentThread<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Listed alongside this particular function was this other similarly-named one; CurrentThreadLite:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>DllImport<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;mscoree&quot;</span>, EntryPoint<span style="color: #008000;">=</span><span style="color: #666666;">&quot;#211&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr Threading_Thread_CurrentThreadLite<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>That’s interesting. It returns a different type, an integer pointer a opposed to a Thread object. But for my purposes I just wanted to uniquely identify a thread. If it’s faster, then it&#8217;s ideal for what I need. The suffix &#8216;lite&#8217; sounds promising!</p>
<p>I tried to see what .NET code actually uses it, it’s these methods:</p>
<p><img class="alignnone size-full wp-image-556" title="CurrentThreadLite" src="http://www.gavpugh.com/wp-content/uploads/2010/04/CurrentThreadLite1.png" alt="CurrentThreadLite" width="440" height="170" /></p>
<p>At least within the .NET executable that I was inspecting. There are probably other .NET library methods that make use of it. I’m not too experienced with the reflector, so I’m totally unsure of a good way of finding them.</p>
<p><strong> </strong></p>
<h4>Lite execution</h4>
<p>So I was curious about whether this ‘lite’ version was faster than the ‘full’ version on Xbox 360. A google search yielded an extremely small number of results for CurrentThreadLite, and variations of it. I figured as part of this small article I may as well have a little go at seeing if it does perform better. It may help someone else out in future who stumbles upon this page.</p>
<p>The main problem though is that there’s no direct accessor to it. Nothing at all. The StringBuilder object makes use of it to maintain thread-safety on its mutable strings, which I’ve touched on in previous articles. Using the same method I described in <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_new">this article</a>, I can grab the private member that stores the ‘IntPtr’ thread.</p>
<p>This does mean that I’ll be adding the overhead of both reflection, and likely some allocations within StringBuilder too. Given the limited set of methods I have to play with, I doubt I’ll end up with anything workable within a game. This really is purely a bit of an educational investigation now, unfortunately there&#8217;s not going to be anything that I&#8217;d consider usable.</p>
<h4>A crude performance test</h4>
<p>I picked out one StringBuilder method which calls CurrentThreadLite: <strong>Append(String)</strong>. You can see the source to this method here:</p>
<p><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_new">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></p>
<p>The .NET library code though calls a method with a different name than the reflector tells us. The prototype of which is:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>MethodImplAttribute<span style="color: #008000;">&#40;</span>MethodImplOptions<span style="color: #008000;">.</span><span style="color: #0000FF;">InternalCall</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color: #0600FF; font-weight: bold;">extern</span> IntPtr InternalGetCurrentThread<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I think I can safely assume this just calls through to <b>CurrentThreadLite</b>.</p>
<p>Anyway, if I pass ‘String.Empty’ as a parameter to Append() it’ll end up doing very little work. But <strong>CurrentThreadLite</strong> will be ran though, so it’d be a good indicator as to whether it’s faster to execute than the ‘full’ one.</p>
<p>Here’s the code I’m testing with, same one million-times loop as before:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder string_builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000000</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Here’s the results:</p>
<table>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Xbox 360 Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>0.407s
</td>
</tr>
</table>
<p>&nbsp;</p>
<p>So it’s over ten times faster than the ‘full’ CurrentThread property accessor, the one I tested further up this article. That’s pretty cool! It makes sense that StringBuilder would use this over CurrentThread, if it were available. If they didn’t, any mutable change to a string would be ten times slower than it is now. That said, it still lags a lot behind PC; being around fifty times slower than that platform.</p>
<p>To reiterate though; unfortunately there&#8217;s no exposed direct access to <b>CurrentThreadLite</b>. As far as I can tell there&#8217;s no workable way of making use of it. I&#8217;d love someone to tell me otherwise though, it&#8217;d be awesome if I could use it.</p>
<h3>StringBuilder though is still pretty slow on Xbox 360</h3>
<p>In a <a href="http://www.gavpugh.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/" target="_new">previous article</a>, I profiled some string manipulation code I’d written. Even though I was implementing alternate methods to what StringBuilder provides, in the end I still called their <strong>Append()</strong>. So I’d be incurring the hit from calling CurrentThreadLite too. It probably explains why the Xbox was running over ten times slower than PC.</p>
<p>I wonder if I can use reflection to grab the raw char[] data, and the string length. Then as long as I keep my code thread-safe by other means, I could work directly on the char[] buffer and concatenate strings myself. This would effectively do away with the overhead of checking what the current thread is, which is within all the existing StringBuilder mutable methods. Even though <b>CurrentThreadLite</b> is seemingly no slouch, it&#8217;s still not exactly cheap.</p>
<p>Something to think about… If it brings performance of StringBuilder in line with PC, then it certainly seems worth it. Whether it&#8217;s worth it for an XNA game though is arguable. Still, I found it interesting looking into this corner of C#.</p>
<h3>References</h3>
<ul>
<li><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Threading/Thread/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Threading/Thread/</a></li>
<li><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; A garbage-free StringBuilder Format() method</title>
		<link>http://www.gavpugh.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/</link>
		<comments>http://www.gavpugh.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 16:42:38 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=472</guid>
		<description><![CDATA[So, another entry in this StringBuilder and garbage series… This time I’m exploring the Format() method, and implementing a new alternative that does not generate any garbage. The existing AppendFormat() method on StringBuilder generates a significant amount of garbage. So in what way does the .NET one generate garbage? Well, the parameter type is ‘object’, [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-475 aligncenter" title="27garbage_600" src="http://www.gavpugh.com/wp-content/uploads/2010/03/27garbage_6001.jpg" alt="" width="600" height="280" /></p>
<p>So, another entry in this StringBuilder and garbage series… This time I’m exploring the Format() method, and implementing a new alternative that does not generate any garbage. The existing AppendFormat() method on StringBuilder generates a significant amount of garbage.</p>
<p>So in what way does the .NET one generate garbage? Well, the parameter type is ‘object’, so you’ll get boxing and unboxing of value types. Since integers and floats are pretty oft-used with Format(), that’s not good news. With CLRProfiler I also see temporary allocations made in ‘String::ToCharArray()’, and ‘String::CtorCharArrayStartLength()’. There’s also more garbage if you use more than three arguments; for that it requires a temporary array to be created.</p>
<p>All in all, it’s not a pretty picture if you want to avoid garbage collections in your game.</p>
<p><span id="more-472"></span></p>
<h3>Variable arguments</h3>
<p>The AppendFormat() method takes a string parameter, then a series of parameter arguments. The amount of these can vary, and they can be of a different types too. So how best pass these in? Well, there are a number of different methods. Take a look at the ones StringBuilder provides as standard:<strong> </strong></p>
<ul>
<li>StringBuilder AppendFormat( string format, params object[] args );</li>
<li>StringBuilder AppendFormat( IFormatProvider provider, string format, params object[] args );</li>
<li>StringBuilder AppendFormat( string format, object arg0 );</li>
<li>StringBuilder AppendFormat( string format, object arg0, object arg1 );</li>
<li>StringBuilder AppendFormat( string format, object arg0, object arg1, object arg2 );</li>
</ul>
<p>Each of these uses object params. Object params are subject to boxing and unboxing with value types. Since I’d want to pass integers and floats through, this isn’t good. The other thing I noticed was that array parameters using the ‘params’ keyword cause a temporary allocation too. Even without using the object type, take this simplified example:<strong> </strong></p>
<p><strong>public void TestMethod( params int[] args );</strong></p>
<p>Any call to this method generates garbage. The ‘params’ keyword essentially converts any params you might specify into an array. The array of integers in this case is allocated as a temporary and then destroyed. The same thing happens when using class types too, not just value types. A different tact is required here.</p>
<p>There were two approaches I explored to support a variable set of arguments, without generating garbage. One of these I went with and will explain now, the other one I explain later on this article in the ‘Things to try’ section. The approach I chose uses generics, and unfortunately a method is required to be implemented for each number of parameters I’d want to support. Other than that though, it’s a really good fit for this problem.</p>
<h3>The implementation</h3>
<p>So, there are two main problems to solve here:</p>
<ul>
<li> Support a variable number of arguments of arbitrary types</li>
<li> Be able to use these types, perform any conversion required and concatenate them onto a StringBuilder</li>
</ul>
<p>For the former, I&#8217;m just using generics. For each number of parameters I need to support, I&#8217;ll need to write a new method. This multiple versions of the same method, but with a different number of parameters isn’t too pretty. It reminds me of C++ template abuse, stuff like the <a href="http://sigslot.sourceforge.net/" target="_blank">sig_slot library</a>.</p>
<p>But here it gets the job done, and it’s kind of your classic C# stuff in a way. There’s no support for default parameters in C#. So for different arguments you generally have to have wrapper methods to support different sets of parameters.</p>
<p>Casting generics is not like C++. My first thought was something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> FormatArgument<span style="color: #008000;">&#40;</span> StringBuilder string_builder, T arg <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> arg<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">int</span> int_arg <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#41;</span>arg<span style="color: #008000;">;</span>
        string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Concat</span><span style="color: #008000;">&#40;</span> int_arg <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>But the straight casting like this is not allowed. There does seem to be a couple of methods to convert types though. At least these were the two I found, both these examples are with integers:</p>
<ul>
<li><strong>Convert.ToInt32( arg )</strong></li>
<li><strong>Arg.ToInt32( System.Globalization.NumberFormatInfo.CurrentInfo )</strong></li>
</ul>
<p>Both have their downfalls. Convert.ToInt32() generates garbage, which makes it unusable for my purpose. The latter one though doesn’t generate garbage, but it is only available on types that implement <strong>IConvertible</strong>. Fortunately all the types I wanted to use (string, int, float) all implement IConvertible. However some other types that would be nice to support, such as Math.Vector don’t. I went with this method, and in turn had to limit the arguments to IConvertibles using the ‘where’ keyword.</p>
<p>That’s about it for the nitty-gritty on some of my decisions. The rest of the code is just a classic char-by-char over the formatted string. It’ll look for the ‘{‘ open curly bracket character and then use the Concat() methods from my previous article to push in the parameters. So, here’s the code:</p>
<p><a href="http://www.gavpugh.com/source/StringBuilderExtFormat.zip"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2010/04/zip_file1.png" alt="Zip File" width="48" height="52" /><strong> StringBuilderExtFormat.zip</strong></a></p>
<h3>Performance</h3>
<p>I was definitely curious as to how my code performs. There&#8217;s certainly more scope for optimization, but I&#8217;m not keen on spending time on it unless it&#8217;s something to worry about. Using the <strong>Stopwatch</strong> class I measured the runtime of this piece of code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">ConcatFormat</span><span style="color: #008000;">&#40;</span>
    <span style="color: #666666;">&quot;Test {0:0.0000} Test {1:X} Test {2} {3}&quot;</span>,
    3<span style="color: #008000;">.</span>45111111f, 0xBEEF, <span style="color: #FF0000;">12345678</span>, <span style="color: #666666;">&quot;Hello World&quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>A nice taxing formatted string with varied parameters. Here’s a table of the performance figures, they are measured from a loop calling this method 1,000,000 times.</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="162" valign="top"></td>
<td colspan="2" width="231" valign="top"><strong>Windows   PC</strong></td>
<td colspan="2" width="245" valign="top"><strong>Xbox   360</strong></td>
</tr>
<tr>
<td width="162" valign="top"></td>
<td width="120" valign="top">.NET’s</td>
<td width="111" valign="top">Mine</td>
<td width="126" valign="top">.NET’s</td>
<td width="118" valign="top">Mine</td>
</tr>
<tr>
<td width="162" valign="top">Unoptimized build<br />
- In debugger</td>
<td width="120" valign="top">2.43s</td>
<td width="111" valign="top">3.23s</td>
<td width="126" valign="top">27.57s</td>
<td width="118" valign="top">32.03s</td>
</tr>
<tr>
<td width="162" valign="top">Optimized build<br />
- In debugger</td>
<td width="120" valign="top">2.43s</td>
<td width="111" valign="top">2.61s</td>
<td width="126" valign="top">27.57s</td>
<td width="118" valign="top">28.43s</td>
</tr>
<tr>
<td width="162" valign="top">Optimized build<br />
- No debugger, jit-ed</td>
<td width="120" valign="top">2.38s</td>
<td width="111" valign="top"><strong>1.84s</strong></td>
<td width="126" valign="top">20.33s</td>
<td width="118" valign="top"><strong>18.03s</strong></td>
</tr>
<tr>
<td width="162" valign="top">Garbage generated</td>
<td width="120" valign="top">284MB</td>
<td width="111" valign="top"><strong>0 bytes</strong></td>
<td width="126" valign="top">381MB</td>
<td width="118" valign="top"><strong>0 bytes</strong></td>
</tr>
</tbody>
</table>
<p>&nbsp;<br />
For both times and garbage, smaller is better! <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The notable thing is that the native AppendFormat() performs the same when optimized or not. I’m not entirely familiar with the in’s and out’s of .NET assemblies just yet. But I do wonder if I could put these routines in a separate library. Then whether I can set things up so that they are jit-ed, regardless of whether my main code module is ran in the debugger or not. Not something I’m too interested in right now, but just throwing it out there. I’m sure google is my friend on this one!</p>
<p>Anyhow, I’m happy that on the final build of the game I’ll have better performance than the stock .NET method. Also with significantly less garbage of course. There’s plenty of scope for optimization on my methods too, they’re pretty much a naïve first-go in all cases. With a little time and effort I think a good chunk could come off these times. Knowing it performs well though is good enough for me right now, I’ll give it more attention down the road if I need to.</p>
<h3>Things to try</h3>
<h4>A Format() that does everything?</h4>
<p>Obviously the version I’ve written doesn’t offer anywhere near the same fully-featured functionality as the stock .NET Format(). I don’t envision myself needing any more features for a game though to be honest. If I did come across something I wanted it wouldn’t be too much of a pain to implement I’m sure. But, take a look at the .NET docs, and the AppendFormat() source code:</p>
<p><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></p>
<p>The AppendFormat() in StringBuilder is the one that is also used by System.String and I’d assume the rest of the .NET code. Using this source and any documentation for the formatting specifiers, it’d be possible to implement the same level of functionality but using my techniques to avoid garbage. Quite a task though I’d think!<br />
&nbsp;</p>
<h4>Supporting arbitrary parameter types</h4>
<p>Another thing to give a go, is a second method of variable arguments I played around with. A method that doesn’t use generics, but instead uses a base class. For an example, here’s a method prototype with two arguments:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> StringBuilder ConcatFormat<span style="color: #008000;">&#40;</span> <span style="color: #0600FF; font-weight: bold;">this</span> StringBuilder string_builder,
    <span style="color: #6666cc; font-weight: bold;">String</span> format_string, FormatArgument arg1, FormatArgument arg2 <span style="color: #008000;">&#41;</span></pre></div></div>

<p>The ‘FormatArgument’ class is an abstract base class. What you’d do is implement subclasses for each supported type, i.e.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> FormatArgumentInt <span style="color: #008000;">:</span> FormatArgument</pre></div></div>

<p>Then have a virtual method for appending the type into the StringBuilder. The crux of this whole technique is in the use of implicit constructors. So that depending on the argument you specify to ConcatFormat(), you’ll get it converted into a new FormatArgument type. Here’s an example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">implicit</span> <span style="color: #0600FF; font-weight: bold;">operator</span> FormatArgument<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> value <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    FormatArgumentInt arg <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FormatArgumentInt<span style="color: #008000;">&#40;</span> value <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> arg<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Hey, this example allocates a temporary class therefore generates garbage when used? Indeed it does, but you can use a pool container to deal with this. Pre-allocating all of these and dealing out pool items when they’re created solves the garbage issue. You’ll also need to manually dispose of them and add them back to the pool.</p>
<p>It’s a lot of work. The big upside is that you can support any types, such as Math.Matrix and Vector. It’d be cool to be able to use those if you’re using Format() for debugging. In my experiments though, performance wasn’t too hot, it was in the region of 1.5-2 times slower than the generics method I detailed earlier. The code also becomes a lot more unwieldy; the generics method looked like a work of art by comparison!</p>
<p>Maybe there’s a way of using the generics method on arbitrary non-IConvertible types? Without incurring garbage on the conversions too of course.<br />
&nbsp;</p>
<h4>Printf</h4>
<p>I like the positional arguments of C#’s Format. C/C++’s printf() stipulates that the argument list has to be used in the same order that the params are specified in the formatting string. This makes the .NET way useful for localizations particularly, where something like:</p>
<p><strong>Player {0} got {1} points!</strong></p>
<p>Could become:</p>
<p><strong>Allez {1} punts spiele {0}!  </strong> &lt;&lt; Just a made-up foreign language</strong></p>
<p>Essentially the translation requires those parameters to appear in a different order. With printf() it’s painful to do this correctly.</p>
<p>That said though if you’ve used printf() for over a decade like I have, switching to Format() might not be quite as fun. So why not implement printf() in C#? It’s really only a minor modification over the code I provide above. I was a little tempted myself, but I really want to stick with doing things the C# way for now. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.convert%28VS.71%29.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.convert%28VS.71%29.aspx</a></li>
<li><a href="http://blog.stevex.net/string-formatting-in-csharp/" target="_blank">http://blog.stevex.net/string-formatting-in-csharp/</a></li>
<li><a href="http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx" target="_blank">http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Avoiding garbage when working with StringBuilder</title>
		<link>http://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/</link>
		<comments>http://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 15:23:54 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[append]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[concat]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[itoa]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=392</guid>
		<description><![CDATA[In my previous coding post, I spoke about some issues with converting a mutable StringBuilder string back to a regular ‘string’ object without generating garbage. Well, specifically without requiring an unnecessary heap allocation. One thing I hinted at was that StringBuilder has a number of other methods which generate garbage too. In fact, there are [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="aligncenter size-full wp-image-418" title="Garbage" src="http://www.gavpugh.com/wp-content/uploads/2010/03/garbage1.jpg" alt="Garbage" width="620" height="300" /></p>
<p>In my <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">previous coding post</a>, I spoke about some issues with converting a mutable StringBuilder string back to a regular ‘string’ object without generating garbage. Well, specifically without requiring an unnecessary heap allocation. One thing I hinted at was that StringBuilder has a number of other methods which generate garbage too. In fact, there are a lot of important fundamental methods which do, which are difficult to live without.</p>
<p>As I&#8217;ve mentioned before, worrying about this sort of thing may not be necessary for the game you&#8217;re working on. It&#8217;s much more of a concern on Xbox 360 than PC, due to the poorly performing garbage collector on 360. If your game isn&#8217;t something that&#8217;s going to remotely push the hardware, or be impacted by dropped frames, then you really don&#8217;t need to worry. This article is just for those who may see this as an issue, and want to explore ways to eliminate this particular method of generating garbage.<br />
<span id="more-392"></span></p>
<h3>Problem StringBuilder methods</h3>
<p>So, here&#8217;s a table of all the methods StringBuilder has. My test case used a StringBuilder constructed with an initial capacity of 1024 characters. This is plenty for anything I threw at it, so any garbage I found with <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=a362781c-3870-43be-8926-862b40aa0cd0&amp;displaylang=en" target="_blank">CLRProfiler</a> was not something associated with reallocating the StringBuilder internal string. In the cases where there&#8217;s garbage generated I&#8217;ve commented with the most interesting or appropriate function in the callstack. In many cases it&#8217;s just exactly the same method, but with the function signature reported by CLRProfiler.</p>
<table border="0" cellspacing="0" cellpadding="0" width="661">
<col width="331"></col>
<col width="71"></col>
<col width="259"></col>
<tbody>
<tr height="20">
<td width="331" height="20"></td>
<td width="71"><span style="text-decoration: underline;"><strong>Garbage</strong></span></td>
<td width="259"><span style="text-decoration: underline;"><strong>Pertinent Allocation / Notes<br />
</strong></span></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(bool value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(byte value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char[] value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(decimal value);</td>
<td><strong>Yes</strong></td>
<td>Append(System.Decimal)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(double value);</td>
<td><strong>Yes</strong></td>
<td>Append(float64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(float value);</td>
<td><strong>Yes</strong></td>
<td>Append(float32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(int value);</td>
<td><strong>Yes</strong></td>
<td>Append(int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(long value);</td>
<td><strong>Yes</strong></td>
<td>Append(int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(object value);</td>
<td><strong>Yes</strong></td>
<td>object::ToString()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(sbyte value);</td>
<td><strong>Yes</strong></td>
<td>Append(int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(short value);</td>
<td><strong>Yes</strong></td>
<td>Append(int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(string value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(uint value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(ulong value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(ushort value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char value, int   repeatCount);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char[] value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(string value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendFormat(&#8230;); <em>(all   five)</em></td>
<td><strong>Yes</strong></td>
<td>In all cases, even without args</td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendLine();</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendLine(string value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">void CopyTo(&#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">int EnsureCapacity(int capacity);</td>
<td><strong>Yes</strong></td>
<td>If capacity param &gt; current capacity</td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">bool Equals(StringBuilder sb);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, bool   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, byte   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char   value);</td>
<td><strong>Yes</strong></td>
<td>String::CtorCharCount()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char[]   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, decimal   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, System.Decimal)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, double   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, float64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, float   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, float32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, int   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, long   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, object   value);</td>
<td><strong>Yes</strong></td>
<td>object::ToString()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, sbyte   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, short   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, string   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, uint   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, ulong   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, ushort   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, string   value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char[]   value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Remove(int startIndex, int   length);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Replace(&#8230;); <em>(all four)</em></td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">override string ToString();</td>
<td><strong>Yes*</strong></td>
<td>See my <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">previous article</a></td>
</tr>
<tr height="20">
<td height="20">string ToString(int startIndex, int   length);</td>
<td><strong>Yes*</strong></td>
<td>String::InternalSubString()</td>
</tr>
</tbody>
</table>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;">
<table style="border-collapse: collapse; width: 495pt;" border="0" cellspacing="0" cellpadding="0" width="661">
<col style="width: 248pt;" width="331"></col>
<col style="width: 53pt;" width="71"></col>
<col style="width: 194pt;" width="259"></col>
<tbody>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt; width: 248pt;" width="331" height="20"></td>
<td class="xl65" style="width: 53pt;" width="71">Garbage</td>
<td class="xl65" style="width: 194pt;" width="259">Pertient Allocation</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(bool value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(byte value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char[] value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(decimal value);</td>
<td class="xl66">Yes</td>
<td>Append(System.Decimal)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(double value);</td>
<td class="xl66">Yes</td>
<td>Append(float64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(float value);</td>
<td class="xl66">Yes</td>
<td>Append(float32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(int value);</td>
<td class="xl66">Yes</td>
<td>Append(int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(long value);</td>
<td class="xl66">Yes</td>
<td>Append(int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(object value);</td>
<td class="xl66">Yes</td>
<td>ToString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(sbyte value);</td>
<td class="xl66">Yes</td>
<td>Append(int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(short value);</td>
<td class="xl66">Yes</td>
<td>Append(int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(string value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(uint value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(ulong value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(ushort value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char value, int   repeatCount);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char[] value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(string value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendFormat(&#8230;); (all   five)</td>
<td class="xl66">Yes</td>
<td>String::ToCharArray(), even without args</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendLine();</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendLine(string value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">void CopyTo(&#8230;); (all)</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">int EnsureCapacity(int capacity);</td>
<td class="xl66">Yes, if capacity param &gt; current capacity</td>
<td>StringBuilder::GetNewString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">bool Equals(StringBuilder sb);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, bool   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, byte   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char   value);</td>
<td class="xl66">Yes</td>
<td>String::CtorCharCount()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char[]   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, decimal   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, System.Decimal)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, double   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, float64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, float   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, float32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, int   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, long   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, object   value);</td>
<td class="xl66">Yes</td>
<td>ToString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, sbyte   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, short   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, string   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, uint   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, ulong   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, ushort   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, string   value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char[]   value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Remove(int startIndex, int   length);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Replace(&#8230;); (all four)</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td class="xl67"></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">override string ToString();</td>
<td class="xl66">Yes</td>
<td>String::InternalCopy()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">string ToString(int startIndex, int   length);</td>
<td class="xl66">Yes</td>
<td>String::InternalSubString()</td>
</tr>
</tbody>
</table>
</div>
<h6><em>* Technically you could describe these as not generating garbage, simply allocating a new string for the client to use. Certainly for the latter of these it makes sense, the term garbage is a little incorrect. But for the former, hence my previous article, it&#8217;s unnecessary and can be avoided with a little work.</em></h6>
<p><em><br />
</em></p>
<p>The common theme for garbage here is type-conversion. Anything that isn&#8217;t a string or char type is pretty much guaranteed to generate it.  &#8216;<strong>bool</strong>&#8216; is an oddball I think probably because it inserts string literals: &#8216;false&#8217; and &#8216;true&#8217;, so no conversion is needed. The other peculiar one is the <strong>Insert( int, char )</strong> one, it generates garbage when logically it doesn&#8217;t really need to. Oddly the .NET library source code says it calls Char.ToString() on the char parameter. Possibly just an oversight in the library?</p>
<p>The reasoning for the type conversions generating garbage, is that they return a temporary string converting that type to a string. This string is then fed into the StringBuilder, and then discarded. Whilst it could have been done in-place, I think the reason why it isn&#8217;t is to support <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">CultureInfo</a> modifiers on the conversion. Where that conversion could take place in a different way based on the passed in CultureInfo. StringBuilder internally uses CultureInfo.CurrentCulture.</p>
<p>I think the implementation chosen was for simplicity and clarity of the type conversions. Writing a system to perform these type conversions in-place <strong>and</strong> have the flexibility of what CultureInfo offers, would have likely made the code significantly more complex. I can understand their reasoning completely.</p>
<h3>Appending numeric types without generating garbage</h3>
<p>For this article I specifically wanted to detail a replacement for those type conversion methods. These are ones you&#8217;d definitely need for a game, for at least your HUD readouts. Since these could be updated every frame, using the garbage-churning .NET library methods isn&#8217;t going to be pretty.</p>
<p>The replacement methodology I used was pretty simple; a number of methods don&#8217;t generate garbage, so use those to build up the string. This effectively means implementing an <a href="http://en.wikipedia.org/wiki/Itoa" target="_blank">itoa()</a> in C#, a conversion of an integer into string form. Floating point numbers too being handled in much the same way. My implementation is via C#&#8217;s extension methods. So the new garbage-free versions of Append() can be called directly on a StringBuilder object, as if they came with the original framework.</p>
<p>Here&#8217;s the code for download:<br />
<a href="http://www.gavpugh.com/source/StringBuilderExtNumeric.cs"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="cs_file" src="http://www.gavpugh.com/wp-content/uploads/2010/03/cs_file1.png" alt="C# File" width="48" height="52" /><strong>StringBuilderExtNumeric.cs</strong></a></p>
<p>Since Append() is already taken, I chose Concat() as my alternative. There&#8217;s additional functionality over what&#8217;s offered by default in StringBuilder, to aid formatting of text. For floats you&#8217;re able to specify the amount of decimal places. For all numeric types you can specify the amount of padding, and the padding character used (most likely zero or space). Lastly, integers can be output with a specific base value, so your code could output hex, binary and octal if so desired.</p>
<p>Here&#8217;s a short made-up example of it&#8217;s usage:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder m_hud_health_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span> <span style="color: #FF0000;">64</span>, <span style="color: #FF0000;">64</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
StringBuilder m_hud_ammo_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span> <span style="color: #FF0000;">64</span>, <span style="color: #FF0000;">64</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> UpdateHUDStrings<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Note: It's sensible to create a wrapper for Concat( string ), which just calls</span>
    <span style="color: #008080; font-style: italic;">// Append() to avoid mixing these method names. When JIT-ing, it would be inlined.</span>
&nbsp;
    m_hud_health_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>                    <span style="color: #008080; font-style: italic;">//&lt; Clear the string</span>
    m_hud_health_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Concat</span><span style="color: #008000;">&#40;</span> GetCurrentHealth<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>   <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_health_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot; / &quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    m_hud_health_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Concat</span><span style="color: #008000;">&#40;</span> GetMaximumHealth<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>   <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
&nbsp;
    m_hud_ammo_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>                      <span style="color: #008080; font-style: italic;">//&lt; Clear the string</span>
    m_hud_ammo_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Concat</span><span style="color: #008000;">&#40;</span> GetBulletsInAmmoClip<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_ammo_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot; ( &quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    m_hud_ammo_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Concat</span><span style="color: #008000;">&#40;</span> GetNumAmmoClips<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>      <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_ammo_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot; )&quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>But, what about Format(), I hear you cry? It can sometimes be easier to format more complex strings, and can result in much cleaner code than multiple appends/concats. Well, I have a garbage-free one of those too. I&#8217;ll cover its implementation next time I write about C# here.</p>
<h3>Some other things to try</h3>
<p>The code I’ve written <span style="text-decoration: line-through;">probably</span> (definitely) could be optimized further. In case you need to do this, or if you’re just curious and want to play around, I’ve got a few ideas of things to try:</p>
<ul>
<li> Different code for the oft-used base ten. You’re now modulo-ing and dividing by a constant, and passing one less parameter around. You can also just add characters by using ( ‘0’ + value ), instead of using the static char array. The static char array is just used since the hex ‘A-F’ don’t follow ‘9’ in the ascii table.</li>
<li> Try using a static char[] array to generate the string you’re about to append, and just call Append() once on the StringBuilder. StringBuilder keeps itself thread-safe and has other overhead on most of its members. So I think this would result in a speedup, by just making one mutable interaction with the StringBuilder.<br />
Keep in mind that you’ll want to make this array a [ThreadStatic] (thread-local store), so that you can use the code on multiple threads without issue.</li>
<li> Take a look at these two websites for some more ideas:<br />
<a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" target="_blank">Coverage  of some common C implementations</a>, along with some performance  comparisons.<br />
<a href="http://sourceforge.net/projects/itoa/" target="_blank">A bit of a different approach using C++</a>, potentially may throw up something applicable to C#.</li>
</ul>
<p>Another thing worth considering is to wrap up the StringBuilder into a new type. Maybe a struct is a good idea, to save making another heap allocation when creating them. The reasoning behind this is to hide away the garbage-generating methods. So all you’re exposing are the safe, garbage-free methods. It also saves you having to awkwardly come up with a different method name, such as ‘Concat()’, like I did. Another win for this methodology is that you could write operator overloads to support ‘+=’, to perform concatenations too.</p>
<h3>References</h3>
<ul>
<li><a href="http://forums.xna.com/forums/p/16395/87923.aspx" target="_blank">http://forums.xna.com/forums/p/16395/87923.aspx</a></li>
<li><a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" target="_blank">http://www.jb.man.ac.uk/~slowe/cpp/itoa.html</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; StringBuilder to String with no garbage</title>
		<link>http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/</link>
		<comments>http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 05:50:32 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=298</guid>
		<description><![CDATA[In my day job I’m a bit of a stickler with memory. I’m at times approaching borderline OCD I think with budgets and fragmentation. Having a good handle on memory usage on a game is very important; once you start pushing a console’s limits you can cause a lot of headaches down the road if [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-299  aligncenter" title="String Garbage" src="http://www.gavpugh.com/wp-content/uploads/2010/03/DrawstringGarbage1.jpg" alt="String Garbage" width="233" height="226" /></p>
<p>In my day job I’m a bit of a stickler with memory. I’m at times approaching borderline OCD I think with budgets and fragmentation. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Having a good handle on memory usage on a game is very important; once you start pushing a console’s limits you can cause a lot of headaches down the road if you’re not mindful of things like memory budgets. Forgetting about fragmentation until it’s a big problem is also a bad idea. Once you’ve started bad practices like this on a game, they tend to snowball and you’re in for a hard uphill battle once they become a problem that needs fixing.</p>
<p>With working in C# and XNA now, the big enemy on the memory front isn’t really fragmentation or running out of available memory. The Xbox 360 has plenty of memory for any project I’d try and tackle myself; coder art for the win! The problem is one of performance, more specifically the lack of performance of the garbage collection system. Garbage collection on the 360 isn’t as full featured as on the full .NET Framework on Windows. It lacks the ‘generational’ model that the full Framework offers, meaning a full collection is performed whenever the system deems it necessary to do one.</p>
<p><span id="more-298"></span>Having random CPU spikes in your game is a nightmare. More so that in the case of garbage collection on 360 there’s little control other than being able to invoke a collection yourself manually. If you’re generating garbage at runtime during gameplay, you are going to see spikes in your frame times. With just a little garbage generated, and if your game isn’t CPU-bound, you may be able to get away with not giving this any attention. However given my nature with this sort of thing, I want to run a tight ship with this being a potential future headache if I don’t do so.</p>
<p>That said, I think for any sort of menu system I’d have, I’d probably be happy to let it generate garbage and then just call GC.Collect() when we go back to gameplay. Giving it a different treatment entirely to how I&#8217;d handle the regular runtime gameplay of the game. It’s all about where it’s important to concentrate efforts to avoid garbage.</p>
<h3>Profiling</h3>
<p>For profiling any garbage my game might generate I use <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=a362781c-3870-43be-8926-862b40aa0cd0&amp;displaylang=en" target="_blank">CLRProfiler for Windows</a>. It gives a nice in-depth analysis of memory usage, it’s pretty much invaluable for dealing with garbage collection problems. It’s almost worth keeping your game always running on a Windows target just so that you can make use of it!</p>
<p>On 360 I use the ‘Remote Performance Monitor’ that comes with the Game Studio SDK. It’s nowhere near as detailed, but it does give a good indication of the severity of any garbage collection issues with your game. Discussing how I use these tools is beyond the scope of this blog post, Google is your friend. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>The String and StringBuilder problem</h3>
<p>The StringBuilder class in C# is the preferred way of working with string manipulation if performance is important. You can avoid it entirely, but you’ll be very likely to end up generating garbage at runtime if you’re exclusively using the string type.</p>
<p>For example, avoid using the ‘+’ operator to concatenate strings. Strings in C# are immutable, meaning they cannot be modified. If you perform this kind of operation, your resultant string will be allocated on the heap. It’s very easy to generate lots of garbage with this sort of code. Something like this monstrosity, which could be run every frame:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> show_world_details <span style="color: #008000;">=</span> “<span style="color: #008000;">&#91;</span> FPS <span style="color: #008000;">:</span>” <span style="color: #008000;">+</span> GetFPS<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> “ P1 Health<span style="color: #008000;">:</span>” <span style="color: #008000;">+</span> GetHealth<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">+</span> “  <span style="color: #008000;">&#93;</span>”<span style="color: #008000;">;</span></pre></div></div>

<p>StringBuilder allows you to work with a mutable string. It provides functionality to concatenate other strings, and other types onto your mutable string. Many of the functions of StringBuilder are completely garbage-free. Many however are not. I’ve a future post in the works which will cover that particular problem in more detail. For now, concatenating other strings onto the StringBulder is garbage-free. So that’s the method I’ll stick to for the sake of this post.</p>
<p>What I wanted to discuss was the conversion of your built up StringBuilder to a string type. There are many functions within the .NET library which only take strings as parameters. Thankfully on the XNA side, the DrawString() rendering routines <strong>do</strong> take a StringBuilder argument natively. However other functions such as those that write debugging output to Visual Studio or the console, only take string parameters. So in walks StringBuilder.ToString()…</p>
<h3>ToString() code</h3>
<p>So does calling ToString() generate garbage? My first expectation was that of course it would, it’d just copy what the string is into a new immutable string object created on the heap. This however is not the case, or at least sometimes it isn’t the case. To avoid beating around the bush here I’ll show you the actual source code of the ToString() method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">String</span> ToString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">String</span> currentString <span style="color: #008000;">=</span>  m_StringValue<span style="color: #008000;">;</span>
    IntPtr currentThread <span style="color: #008000;">=</span> m_currentThread<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>currentThread <span style="color: #008000;">!=</span> Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">InternalGetCurrentThread</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">InternalCopy</span><span style="color: #008000;">&#40;</span>currentString<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">2</span> <span style="color: #008000;">*</span>  currentString<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;</span>lt<span style="color: #008000;">;</span> currentString<span style="color: #008000;">.</span><span style="color: #0000FF;">ArrayLength</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">InternalCopy</span><span style="color: #008000;">&#40;</span>currentString<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008000;">&#125;</span>
&nbsp;
    currentString<span style="color: #008000;">.</span><span style="color: #0000FF;">ClearPostNullChar</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    m_currentThread <span style="color: #008000;">=</span> IntPtr<span style="color: #008000;">.</span><span style="color: #0000FF;">Zero</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span>  currentString<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Bit hairy, no? InternalCopy() is the function which will allocate a copy of the string on the heap and return it. The function can actually return the internal string without making any copies. Specifically the first time it’s called, and if the string makes use of at least 50% of the StringBuilder capacity. The ‘m_currentThread’ member being set to zero will effectively mean that the next time any sort of mutable operation is performed on the StringBuilder; be it clearing the string, or appending to it. The StringBuilder will allocate a new string on the heap. Each of the mutable methods of StringBuilder check the ‘m_currentThread’ and ensure that the StringBuilder owns the particular string. The way ToString() works, it’s effectively giving away ownership of that string and will start with a fresh one on the next mutable operation.</p>
<p>The reasoning behind this thread noting, as well as keeping the String returned by ToString() completely immutable, is to keep StringBuilder thread-safe. There’s comments within the code that detail the potential race condition that could occur, which I have omitted above. You can see them in full <a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">here</a>.</p>
<p>The other reason for making the copy is in the case that the user is making inefficient use of memory. If we’re only using a tiny portion of the StringBuilder capacity, the .NET authors deemed that it’s more efficient to return a copy instead of making reference to the full big string.</p>
<p>If I want to re-use a StringBuilder object, say for some kind of readout I might want Visual Studio to display in the debugging output window. I’m out of luck garbage-wise. I may avoid generating a copy of the string the first time I call it, but if I’m reusing the StringBuilder, it’s going allocate a new string on the heap for me when I call the next mutable method on it.</p>
<h3>The solution</h3>
<p>What I wanted was direct access to the string that the StringBuilder works with. <span style="text-decoration: line-through;">Doing this on Windows with ‘unsafe’ code is most likely straightforward, but I want to target 360 so that’s a non-starter. On the 360 you’re bound by the shackles of the Compact Framework, if it’s not in there, you can’t use it.</span></p>
<p>Thanks to <a href="http://www.codeproject.com/KB/dotnet/strings.aspx" target="_blank">this article</a> though, I was able to track down a method to be able to access that internal string object which the StringBuilder works with. It’s effectively doing something the .NET library authors don’t want you to do, grabbing that private member (oo-er). Thankfully this also works on 360!</p>
<p>Here’s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #6666cc; font-weight: bold;">string</span> my_string <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span>my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
    <span style="color: #666666;">&quot;m_StringValue&quot;</span>,
    <span style="color: #000000;">System.<span style="color: #0000FF;">Reflection</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">BindingFlags</span><span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Reflection</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">BindingFlags</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span> my_stringbuilder <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Reflection isn’t too pretty, eh? But here it’s a nice devious means to an end. Reflection isn’t too hot performance-wise, so I’d recommend grabbing the internal string just the once for the StringBuilder you’ll be working with. Stash it away as a member of a class or something, and you’ll then have the string to pass along to whatever function you wish. Now we’re no longer worrying about the ToString() generating garbage for us; success!</p>
<p>Here&#8217;s a bit of sample code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder my_stringbuilder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span> <span style="color: #FF0000;">32</span>, <span style="color: #FF0000;">32</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> my_string <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span>my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
	<span style="color: #666666;">&quot;m_StringValue&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span> my_stringbuilder <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;This &quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Is &quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;A &quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Test!&quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// my string will be &quot;This Is A Test!&quot;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span> my_string <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// This second append would have resulted in a new heap allocation</span>
<span style="color: #008080; font-style: italic;">// if I'd used ToString() above.</span>
my_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot; Yay!&quot;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span> my_string <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I’d advise creating your StringBuilder objects with the two integer parameters contructor. As well as preallocating the string, you’ll also be putting a cap on the capacity:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Creates an empty StringBuilder with a minimum capacity of capacity</span>
<span style="color: #008080; font-style: italic;">// and a maximum capacity of maxCapacity.</span>
<span style="color: #0600FF; font-weight: bold;">public</span> StringBuilder<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> capacity, <span style="color: #6666cc; font-weight: bold;">int</span> maxCapacity<span style="color: #008000;">&#41;</span></pre></div></div>

<p>Meaning it’ll never grow in size, or make any more heap allocations after it’s initially constructed. If that were to happen, the string object you grabbed is no longer linked to the StringBuilder. You&#8217;d need to redo the reflection call to grab the new string that the StringBuilder owns.</p>
<p>So by using that constructor, this means if you grab the internal string you’re guaranteed to keep the reference to the StringBuilder’s mutable string forever. The one key exception here though is if you work with the StringBuilder on another thread. In that case, you’ll be subject to the same issues as before.</p>
<p>I’ll revisit StringBuilder here again in future, to cover some of it’s other shortcomings with regard to generating garbage.</p>
<h3>References</h3>
<ul>
<li><a href="http://www.codeproject.com/KB/dotnet/strings.aspx" target="_blank">http://www.codeproject.com/KB/dotnet/strings.aspx</a></li>
<li><a href="http://blogs.msdn.com/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx" target="_blank">http://blogs.msdn.com/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx</a></li>
<li><a href="http://blogs.msdn.com/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-xna-part-2-gc-and-tools.aspx" target="_blank">http://blogs.msdn.com/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-xna-part-2-gc-and-tools.aspx</a></li>
<li><a href="http://blogs.msdn.com/stevenpr/archive/2004/07/26/197254.aspx" target="_blank">http://blogs.msdn.com/stevenpr/archive/2004/07/26/197254.aspx</a></li>
</ul>
<p><font color=red></p>
<h3>Addendum: XNA 4.0</h3>
<p>Under XNA 4.0 the technique described doesn&#8217;t work for Windows Phone 7, nor for PC Windows. It does however still function correctly for the Xbox 360.</p>
<p>See this <a href="http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/">blog post</a> for more information about the state of play under XNA 4.0.<br />
</font></p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
	</channel>
</rss>

