<?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>Olhovsky &#187; XNA</title>
	<atom:link href="http://www.olhovsky.com/category/xna/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.olhovsky.com</link>
	<description>Miscellaneous Coding</description>
	<lastBuildDate>Thu, 03 Jun 2010 16:30:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fields vs. properties performance on the Xbox 360.</title>
		<link>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/</link>
		<comments>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 20:32:00 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=140</guid>
		<description><![CDATA[I took Sam Allen&#8217;s performance test and ran a similar test (below) on the Xbox 360 with XNA.

static string _backing; // Backing store for property
static string Property  // Getter and setter
{
    get
    {
        return _backing;
    }
   [...]]]></description>
			<content:encoded><![CDATA[<p>I took <a href="http://dotnetperls.com/property-test">Sam Allen&#8217;s performance test</a> and ran a similar test (below) on the Xbox 360 with XNA.</p>
<pre class="brush:c#">
static string _backing; // Backing store for property
static string Property  // Getter and setter
{
    get
    {
        return _backing;
    }
    set
    {
        _backing = value;
    }
}
static string Field;    // Static field

public FieldPropertyTest(Game game)
    : base(game)
{

    long[] results1 = new long[10];
    long[] results2 = new long[10];

    Property = "string";
    Field = "string";
    const int m = 1000000;
    for (int x = 0; x < 10; x++) // Ten tests
    {
        Stopwatch s1 = new Stopwatch();
        s1.Start();
        for (int i = 0; i < m; i++) // Test property
        {
            Property = "string";
            //if (Property == "cat")
            //{
            //}
        }
        s1.Stop();
        Stopwatch s2 = new Stopwatch();
        s2.Start();
        for (int i = 0; i < m; i++) // Test field
        {
            Field = "string";
            //if (Field == "cat")
            //{
            //}
        }
        s2.Stop();
        results1[x] = s1.ElapsedMilliseconds;
        results2[x] = s2.ElapsedMilliseconds;
    }
}</pre>
<p>The results:</p>
<p><strong>Get:</strong><br />
Property: 341 ms<br />
Field: 307 ms</p>
<p><strong>Set:</strong><br />
Property: 85 ms<br />
Field: 66 ms</p>
<p>This performance difference from the more robust .NET CLR used in Allen's tests is owing to the fact that the .NET Compact CLR (which the Xbox 360 uses) doesn't inline functions at all -- to my knowledge.</p>
<p>Of course, the small size of the numbers above is good news -- it took 10 million gets on a field to produce a 34ms difference.<br />
It's hard to imagine a scenario where using a field in place of a property would be a relatively large enough performance gain to affect your framerate.</p>
<p>There are also the usual <a href="http://blogs.msdn.com/shawnhar/archive/2009/07/14/the-perils-of-microbenchmarking.aspx">caveats with micro-benchmarks</a> like these, and the difference may be smaller (or larger) than what you see above, in real-world uses.</p>
<p>So, I'd take <a href="http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html">Jeff Atwood's advice</a> and simply always use (auto-)properties, unless you have a very tight performance sensitive loop that is accessing many properties.</p>
<p>Edit:<br />
The <a href="http://blogs.msdn.com/b/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-the-xna-framework-1-0.aspx?wa=wsignin1.0">NetCF team blog</a> states that getters/setters are inlined, which is probably a source of some confusion. It's also possible that my results above are wrong, if I've fallen into a micro benchmarking trap. Let me know if you find some results opposing what I've written above.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Foreach through non-primitive types creates garbage.</title>
		<link>http://www.olhovsky.com/2009/09/code-common-to-many-xna-examples-generates-unneccesary-garbage/</link>
		<comments>http://www.olhovsky.com/2009/09/code-common-to-many-xna-examples-generates-unneccesary-garbage/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 02:44:42 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[garbage collection]]></category>
		<category><![CDATA[speed up XNA]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=81</guid>
		<description><![CDATA[Time and again I have seen code like this used in XNA tutorials.

effectDrawBlock.Begin();
foreach (EffectPass pass in effectDrawBlock.CurrentTechnique.Passes)
{
    pass.Begin(); 

    gd.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 35, 0, 70); 

    pass.End();
}
effectDrawBlock.End();

When you use a foreach over an array of ints, you will not create garbage, and it&#8217;s fast, so that&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Time and again I have seen code like this used in XNA tutorials.</p>
<pre class="brush:c#">
effectDrawBlock.Begin();
foreach (EffectPass pass in effectDrawBlock.CurrentTechnique.Passes)
{
    pass.Begin(); 

    gd.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 35, 0, 70); 

    pass.End();
}
effectDrawBlock.End();
</pre>
<p>When you use a foreach over an array of ints, you will not create garbage, and it&#8217;s fast, so that&#8217;s perfectly okay.</p>
<p>However, in the above code, &#8220;EffectPass pass in&#8221; creates a managed effect pass object, used to iterate through the collection. That object then needs to be handled by the garbage collector later.</p>
<p>The fix is to use a for loop when iterating over non-primitive types.<br />
In my case, by changing my code to something more like what you see below, I was able to reduce the number of managed objects generated by my code from 2500/sec to 200/sec as measured by the XNA Framework Remote Perf Monitor.</p>
<pre class="brush:c#">effectDrawBlock.Begin();
for (int i = 0; i < effectDrawBlock.CurrentTechnique.Passes.Count; i++)
{
    effectDrawBlock.CurrentTechnique.Passes[i].Begin();

    gd.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 35, 0, 70);

    effectDrawBlock.CurrentTechnique.Passes[i].End();
}
effectDrawBlock.End();</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2009/09/code-common-to-many-xna-examples-generates-unneccesary-garbage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ToString Garbage Creation in C#</title>
		<link>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/</link>
		<comments>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 05:24:39 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[garbage collector]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=70</guid>
		<description><![CDATA[I profiled my XNA game project today using the XNA Framework Remote Perf Monitor and discovered that I was generating about 8000 more manage objects per second than I was expecting to.
It turns out that this code was generating 7400 managed objects per second:
            [...]]]></description>
			<content:encoded><![CDATA[<p>I profiled my XNA game project today using the XNA Framework Remote Perf Monitor and discovered that I was generating about 8000 more manage objects per second than I was expecting to.</p>
<p>It turns out that this code was generating 7400 managed objects per second:</p>
<pre class="brush:c#">            text[0] = "FPS: " + fps.FPS.ToString();
            text[1] = "charPos: " + charPos.ToString();
            text[2] = "tLOD: " + tLOD.ToString();
            text[3] = "tTris: " + tTris.ToString();
            text[4] = "tBlocksDrawn: " + tBlocksDrawn.ToString();
            text[5] = "tBlocksCulled: " + tBlocksCulled.ToString();
            text[6] = "drawCodeTime: " + drawCodeTime.ToString();
</pre>
<p>A complicated optimization for code that isn&#8217;t even going to get compiled into the release build would be silly. The easiest fix here is to only periodically update the content of these strings (say, once per second, instead of once per frame.)<br />
Also, some of the garbage generation could be reduced by separating the arrays into one array for the static strings &#8220;drawCodeTime: &#8221; for example and then drawCodeTime.ToString() in a separate string. That would still leave thousands of objects per second created, sadly.</p>
<p>If you have a game that relies on many string conversions, your best bet is to use StringBuilder objects (which have predefined size) and replace subsections of those strings with the new string using the .Replace method that StringBuilders have built-in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Convert greyscale images to Alpha8 format with a Custom Content Processor in XNA 3.1.</title>
		<link>http://www.olhovsky.com/2009/09/convert-greyscale-images-to-alpha8-format-with-a-custom-content-processor-in-xna-3-1/</link>
		<comments>http://www.olhovsky.com/2009/09/convert-greyscale-images-to-alpha8-format-with-a-custom-content-processor-in-xna-3-1/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 01:34:31 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[alpha8]]></category>
		<category><![CDATA[content pipeline]]></category>
		<category><![CDATA[custom content processor]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=62</guid>
		<description><![CDATA[I noticed that at least two terrain engine examples in XNA are reading heightmap images into 4 channel textures instead of single channel textures.
To create a custom content processor that will permit you to convert any Texture2D compatible input format into an Alpha8 format texture, do the following:
Right click your game solution -> add new [...]]]></description>
			<content:encoded><![CDATA[<p>I noticed that at least two terrain engine examples in XNA are reading heightmap images into 4 channel textures instead of single channel textures.</p>
<p>To create a custom content processor that will permit you to convert any Texture2D compatible input format into an Alpha8 format texture, do the following:</p>
<p>Right click your game solution -> add new item<br />
Under XNA 3.1 select Custom Content Pipeline, and replace the default class in this solution with this code:</p>
<pre class="brush:c#">
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using Microsoft.Xna.Framework;
using System.ComponentModel;

namespace ContentPipelineExtension1
{
    [ContentProcessor]
    [DesignTimeVisible(true)]
    class HeightMapTextureProcessor : ContentProcessor<TextureContent,TextureContent>
    {
        /// <summary>
        /// Process converts displacement maps to Alpha8 textures.
        /// </summary>
        public override TextureContent Process(TextureContent input,
            ContentProcessorContext context)
        {
            // Convert to data that we can work with:
            input.ConvertBitmapType(typeof(PixelBitmapContent<Vector4>));

            // Select first mipmap, there should only be one:
            MipmapChain mipmapChain = input.Faces[0];

            // There should only be one bitmap, but it doesnt hurt to write this loop:
            foreach (PixelBitmapContent<Vector4> bitmap in mipmapChain)
            {
                for (int x = 0; x < bitmap.Width; x++)
                {
                    for (int y = 0; y < bitmap.Height; y++)
                    {
                        Vector4 pixel = bitmap.GetPixel(x, y);

                        // Move R channel to A channel:
                        bitmap.SetPixel(x, y, new Vector4(0, 0, 0, pixel.X));
                    }
                }
            }

            // Alpha8 contains values from 0 - 1 in the W channel.
            input.ConvertBitmapType(typeof(PixelBitmapContent<Alpha8>));

            input.GenerateMipmaps(false);
            return input;
        }
    }
}
</pre>
<p>Now add a reference to your CustomContentPipeline1 solution in the &#8220;Content&#8221; module in your game solution.</p>
<p>Right click on the heightmap file(s) that you wish to be converted to Alpha8 and select the HeightMapTextureProcessor as the content processor.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2009/09/convert-greyscale-images-to-alpha8-format-with-a-custom-content-processor-in-xna-3-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
