<?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>Bitmatic &#187; Compact Framework</title>
	<atom:link href="http://bitmatic.com/category/compact-framework/feed" rel="self" type="application/rss+xml" />
	<link>http://bitmatic.com</link>
	<description>Defragmenting a .NET programmers brain</description>
	<lastBuildDate>Tue, 13 Jul 2010 13:15:58 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>String &amp; StringBuilder performance in the Compact Framework</title>
		<link>http://bitmatic.com/compact-framework/string-stringbuilder-performance-in-the-compact-framework</link>
		<comments>http://bitmatic.com/compact-framework/string-stringbuilder-performance-in-the-compact-framework#comments</comments>
		<pubDate>Tue, 28 Jul 2009 17:01:48 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[string]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=395</guid>
		<description><![CDATA[Here&#8217;s a few general guidelines when working with strings:

Don&#8217;t concatenate strings &#8211; use a StringBuilder instead
Whenever possible initialize the StringBuilder with enough capacity to avoid re-allocations
Excessive concatenation of strings will be several orders of magnitude slower than using a StringBuilder
String.Format() &#038; StringBuilder.AppendFormat() are significantly slower than just using the +operator or Append() &#8211; but may [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a few general guidelines when working with strings:</p>
<ul>
<li>Don&#8217;t concatenate strings &#8211; use a StringBuilder instead</li>
<li>Whenever possible initialize the StringBuilder with enough capacity to avoid re-allocations</li>
<li>Excessive concatenation of strings will be several orders of magnitude slower than using a StringBuilder</li>
<li>String.Format() &#038; StringBuilder.AppendFormat() are significantly slower than just using the +operator or Append() &#8211; but may be more readable</li>
<li>When performance optimizing an application &#8211; string usage is a good place to start</li>
</ul>
<h3>Don&#8217;t concatenate strings</h3>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx">StringBuilder</a> is an often overlooked class, that can be used to solve a lot of performance problems in your applications.<br />
To give an example of how ineffective the basic string can be, take a look at the following code that builds 2 large strings by concatenating 1000 times to the same string using String and StringBuilder:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="kwrd">string</span> s = <span class="kwrd">string</span>.Empty;
<span class="kwrd">for</span> (<span class="kwrd">int</span> j = 0; j &lt; 1000; j++)
{
  s += <span class="str">"Test of string performance."</span>;
}

StringBuilder sb = <span class="kwrd">new</span> StringBuilder();
<span class="kwrd">for</span> (<span class="kwrd">int</span> j = 0; j &lt; 1000; j++)
{
  sb.Append(<span class="str">"Test of string performance."</span>);
}
</pre>
<p>Performance is measured on my HTC S710 moblie phone. The performance difference is very noticeable.</p>
<ul>
<li>The String implementation takes about 800ms</li>
<li>The StringBuilder implementation takes about 12ms</li>
</ul>
<p>StringBuilder is almost 70 times faster than String in this particular example and initializing the StringBuilder with enough capacity up front will shave another 2ms off. I have done tons of optimizations on Compact Framework applications over the years, and the first thing i usually do is replace String with StringBuilder in code similar to the above example.</p>
<h3>Immutable strings &#8211; blessing or curse?</h3>
<p>Strings in the .NET framework are immutable &#8211; meaning that once they are created they can not be changed. It is a design decision from the .NET framework designers, that allows for a lot of optimizations, but also cost performance under certain circumstances.<br />
This is the main reason the String concatenation from before is so slow. Every time the strings are concatenated, a new String is created, and the old one is left for the garbage collector. At least a thousand strings of increasing size are created, copied and garbage collected for no good reason. It is amazingly ineffective.</p>
<h3>StringBuilder &#8211; definitely a blessing!</h3>
<p>The StringBuilder is the thing to use, when handling and manipulating large strings. It holds the string in an internal array that it grows as needed. This enables a very fast append that only rarely allocates anything new. In my test the StringBuilder initially had a capacity of 64 bytes, and grew to double size whenever needed, but implementations may vary.<br />
This behaviour means that you can optimize performance even further by initializing the StringBuilder to a size that is slightly larger than what you expect the final string to be &#8211; thereby removing the need to ever re-allocate.</p>
<h3>A word or two about String.Format()</h3>
<p>I always assumed that using String.Format() to splice strings with variables was the fastest way of doing it. Tests show, however, that it is not&#8230;<br />
I have made test of 4 different ways of accomplishing the same thing:<br />
<!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">
<span class="rem">//using string</span>
<span class="kwrd">string</span> x = <span class="str">"Test of string performance."</span> + 1 + 2 + <span class="str">"hello"</span>;
<span class="kwrd">string</span> x = <span class="kwrd">string</span>.Format(<span class="str">"Test of string performance.{0}{1}{2}"</span>, 1, 2, <span class="str">"hello"</span>);

<span class="rem">//using StringBuilder</span>
sb.Append(<span class="str">"Test of string performance."</span>).Append(1).Append(2).Append(<span class="str">"hello"</span>);
sb.AppendFormat(<span class="str">"Test of string performance.{0}{1}{2}"</span>, 1, 2, <span class="str">"hello"</span>);</pre>
<p>The results are similar for both the String and StringBuilder. Using the +operator or chained appends is <b>roughly twice as fast</b> as using the Format() method. This came as a bit of a surprise to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/compact-framework/string-stringbuilder-performance-in-the-compact-framework/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Single instance applications in Windows CE</title>
		<link>http://bitmatic.com/compact-framework/single-instance-applications-in-windows-ce</link>
		<comments>http://bitmatic.com/compact-framework/single-instance-applications-in-windows-ce#comments</comments>
		<pubDate>Mon, 13 Jul 2009 18:22:36 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[native code]]></category>
		<category><![CDATA[Windows CE]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=370</guid>
		<description><![CDATA[I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself.
I was a bit surprised that there is no [...]]]></description>
			<content:encoded><![CDATA[<p>I programmed a Windows CE application last month that had as a requirement that only one instance could run at the same time. Had it been Windows Mobile, this had been handled by the OS, but on Windows CE you have to take care of this yourself.<br />
I was a bit surprised that there is no easy way of accomplishing this. Searching the internet gave me basically no easy answer either, but there seems to be 3 standard ways of accomplishing this.</p>
<ul>
<li>Write a dummy text file on startup, and check the existance of this file.</li>
<li>Write to a registry-key on startup, and use that as a &#8220;mutex&#8221;.</li>
<li>Use a named mutex with a system-wide scope.</li>
</ul>
<p>Obviously the first two have the problem that they may break the program, if the program exits without resetting the file/registry-key used as a pseudo-mutex. They are also very crude and not very elegant&#8230;. But that&#8217;s up to personal taste i guess.<br />
I went for the third choice; The named mutex.</p>
<h3>The named mutex in Windows CE</h3>
<p>The .NET Compact Framework does not support named mutexes. Luckily Windows CE does however, and it can be imported through a few functions in coredll.dll.<br />
A named mutex is an object created by the OS with a name specified on creation. The actual functionality of the object is not very interesting right now. The interesting bit is that only one object can exist with any given name. If you try to create another object with the same name, you get an error.<br />
Basically, if you create a named mutex with the name of the application itself, this can be used to ensure that only one instance of the application can be run.</p>
<h3>Wrapping it up</h3>
<p>I decided to wrap it all up nicely in a class, so that it will be easy to use. The class is called SingleInstanceApplication, and here is what i came up with:</p>
<pre class="csharpcode">
<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Windows.Forms;
<span class="kwrd">using</span> System.Runtime.InteropServices;
<span class="kwrd">using</span> System.Reflection;

<span class="kwrd">namespace</span> Bitmatic
{
  <span class="kwrd">static</span> <span class="kwrd">class</span> SingleInstanceApplication
  {
    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> IntPtr CreateMutex(IntPtr Attr, <span class="kwrd">bool</span> Own, <span class="kwrd">string</span> Name);

    [DllImport(<span class="str">"coredll.dll"</span>, SetLastError = <span class="kwrd">true</span>)]
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">extern</span> <span class="kwrd">bool</span> ReleaseMutex(IntPtr hMutex);

    <span class="kwrd">const</span> <span class="kwrd">long</span> ERROR_ALREADY_EXISTS = 183;

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Run(Form frm)
    {
      <span class="kwrd">string</span> name = Assembly.GetExecutingAssembly().GetName().Name;
      IntPtr mutexHandle = CreateMutex(IntPtr.Zero, <span class="kwrd">true</span>, name);
      <span class="kwrd">long</span> error = Marshal.GetLastWin32Error();

      <span class="kwrd">if</span> (error != ERROR_ALREADY_EXISTS)
        Application.Run(frm);

      ReleaseMutex(mutexHandle);
    }
  }
}</pre>
<p>Feel free to steal&#8230;.<br />
The class imports the two native functions for creating and destroying mutexes, and has only a single public function.<br />
The Run function tries to create a mutex with the name of the application. It then checks the error code returned, to see if the mutex already exists, and if it doesn&#8217;t; starts the application. Finally it releases the mutex.<br />
Very simple, and quite a bit more elegant than the file/registry based solutions.</p>
<h3>Using it</h3>
<p>Using the class is very very simple. Just add the class itself to your project, open up Program.cs and replace:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  Application.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>with:</p>
<pre class="csharpcode">
[MTAThread]
<span class="kwrd">static</span> <span class="kwrd">void</span> Main()
{
  SingleInstanceApplication.Run(<span class="kwrd">new</span> Form1());
}</pre>
<p>You only really changed one line, and now you have an application that is guaranteed to run  only as a single instance.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/compact-framework/single-instance-applications-in-windows-ce/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Profiling for the Compact Framework</title>
		<link>http://bitmatic.com/compact-framework/profiling-for-the-compact-framework</link>
		<comments>http://bitmatic.com/compact-framework/profiling-for-the-compact-framework#comments</comments>
		<pubDate>Fri, 15 May 2009 10:30:44 +0000</pubDate>
		<dc:creator>Jakob</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://bitmatic.com/?p=320</guid>
		<description><![CDATA[Just wanted to share with everyone that there is a .NET Profiler that works with the Compact Framework. It is made by a Danish company called Eqatec and best of all; It is completely free.
A long search has ended
I have been looking for something like this for several years, but until the Eqatec profiler, no [...]]]></description>
			<content:encoded><![CDATA[<p>Just wanted to share with everyone that there is a <a href="http://www.eqatec.com/tools/profiler">.NET Profiler</a> that works with the Compact Framework. It is made by a Danish company called <a href="http://www.eqatec.com">Eqatec</a> and best of all; It is completely free.</p>
<h3>A long search has ended</h3>
<p>I have been looking for something like this for several years, but until the Eqatec profiler, no profiler has been able to profile mobile applications. When working with the Compact Framework you often find yourself in situation where performance is an issue. Many times you can make educated guesses as to where the bottlenecks may be, but at other times you are left pretty clueless.<br />
Attach a decent profiler, and your bottlenecks will be clear as ice.</p>
<h3>Does it work?</h3>
<p>When the <a href="http://www.eqatec.com/tools/profiler">Eqatec profiler</a> was released I immediately put it into work with profiling an application that had some performance issues during initial startup. We had tried solving these by guesswork, but it hadn&#8217;t helped a lot.<br />
Within 2 hours of attaching the profiler, I had cut the startup time to a fraction of what it was before.</p>
<p>There is a small issue that you need to be aware of with this profiler. Because of the way it works, by instrumenting the code, it adds a little bit of overhead to every function call. This means that small functions that get called a lot will appear to be more time consuming than they really are, because most of the time used is actually the overhead. This is something to look out for, when deciding which functions to try to optimize. It would be really nice if Eqatec could find a way to compensate for this overhead.</p>
<p>Other than that the profiler works like a charm. And by the way &#8211; I am not paid to write this, I just like the product a lot.</p>
]]></content:encoded>
			<wfw:commentRss>http://bitmatic.com/compact-framework/profiling-for-the-compact-framework/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
