<?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>Jayway Team Blog &#187; performance</title>
	<atom:link href="http://blog.jayway.com/tag/performance/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 28 Jan 2012 15:53:55 +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>IntelliJ IDEA performance improvement</title>
		<link>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/</link>
		<comments>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 17:26:58 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[home directory]]></category>
		<category><![CDATA[idea]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9443</guid>
		<description><![CDATA[Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but [...]]]></description>
			<content:encoded><![CDATA[<p>Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but before you start coding you should make sure you know how the <a href="http://en.wikipedia.org/wiki/Home_directory">home directory</a> of your computer is setup and configure IntelliJ IDEA accordingly. From the <a href="http://devnet.jetbrains.net/docs/DOC-181">documentation</a>:</p>
<blockquote><p>
In some environments user's home directory is located on the mapped network drive which in unacceptable for IntelliJ IDEA. You'll notice the huge performance degradation.
</p></blockquote>
<h2>What is the problem?</h2>
<p>There are some good motives for keeping the home directory mounted to a network folder rather than on the local hard drive. For example, all user settings and user documents can be backed up centrally, and the user could potentially log in to any computer and have the same user environment. However, there are also some drawbacks. Depending on how the home folder is configured, there will either be a remote network call for each file access, or the file changes will be executed as a batch job at scheduled intervals or specific events such as logging off the computer.</p>
<p>The second part of the problem is that IntelliJ IDEA produces quite a lot of data, typically several hundred megabytes, besides the anticipated artifacts. The data consists of IDE plugins, configuration files, log files, but the vast majority is internal cache files. By default, the data is written to a hidden <i>.IntelliJIdea10/</i> folder in your home directory.</p>
<p>If you combine these two factors, the performance will suffer. How much depends on the bandwidth of your network, something that I became painfully aware of when I logged in remotely to the customer's network via a slow VPN connection.</p>
<h2>Solution</h2>
<p>Avoid network overhead by configuring IntelliJ IDEA to cache data on your local computer instead of in your home folder. A recent customer used Windows XP as their working environment, the instructions below are based on that experience.</p>
<ol>
<li>
Create a new directory on a <i>local</i> harddrive that IntelliJ IDEA can use, e.g. <i>C:/.IntelliJIdea10/</i>. Hint, you cannot create a library starting with a "." from Windows Explorer, you have to use the <code>mkdir</code> command from the terminal.
</li>
<li>
Locate the <i>idea.properties</i> file in the <i>bin</i> directory in IntelliJ IDEA's installation directory. The default location is <i>C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 10.5.1\bin</i>.
</li>
<li>
Change the relevant properties to point to the recently created directory:</p>
<pre class="brush:xml">
# path to IDEA config folder. Make sure you're using forward slashes
idea.config.path=C:/.IntelliJIdea10/config

# path to IDEA system folder. Make sure you're using forward slashes
idea.system.path=C:/.IntelliJIdea10/system

# path to user installed plugins folder. Make sure you're using forward slashes
idea.plugins.path=C:/.IntelliJIdea10/config/plugins
</pre>
</li>
</ol>
<h2>Considerations</h2>
<p>Consider <i>not</i> to change the <i>idea.config.path</i> property if you are using several different computers and you would like to have the same configuration on all machines. Additionally, if you are using IntelliJ IDEA Ultimate, i.e. the commercial version of the tool, you should also make a cautious decision about whether or not to keep this property unchanged, because the license file is stored in the denoted directory. On the other hand, if you always use the same computer you might as well change this property together with the other properties, so that all IntelliJ IDEA files are stored in the same location.</p>
<h2>References</h2>
<ul>
<li>IDEA files location: <a href="http://devnet.jetbrains.net/docs/DOC-181">http://devnet.jetbrains.net/docs/DOC-181</a></li>
<li>IDEA license key: <a href="http://devnet.jetbrains.net/docs/DOC-200">http://devnet.jetbrains.net/docs/DOC-200</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dapper-dot-net aka Micro-ORM</title>
		<link>http://blog.jayway.com/2011/05/23/dapper-dot-net-aka-micro-orm/</link>
		<comments>http://blog.jayway.com/2011/05/23/dapper-dot-net-aka-micro-orm/#comments</comments>
		<pubDate>Mon, 23 May 2011 12:20:45 +0000</pubDate>
		<dc:creator>Björn Carlsson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/2011/05/23/dapper-dot-net-aka-micro-orm/</guid>
		<description><![CDATA[a simple object mapper for .NET After listening to Hanselminutes show #262 I became curious and have looked a bit at Dapper to check what it really is. First of all, it’s implemented as a single file you can drop in your project. It’s created for and at stackoverflow. I heard somewhere that it should [...]]]></description>
			<content:encoded><![CDATA[<h2>a simple object mapper for .NET</h2>
<p>After listening to <a href="http://www.hanselminutes.com/default.aspx?showID=282" target="_blank">Hanselminutes show #262</a> I became curious and have looked a bit at Dapper to check what it really is.</p>
<p>First of all, it’s implemented as a <a href="http://code.google.com/p/dapper-dot-net/source/browse/Dapper/SqlMapper.cs" target="_blank">single file</a> you can drop in your project. It’s created for and at <a href="http://stackoverflow.com/" target="_blank">stackoverflow</a>. I heard somewhere that it should be 400 lines, but it looks more like 1200. It’s nice that I can understand much of how the ORM works just by browsing this file. But there are a few methods with a lot of il.Emit, which I can just hope works fine.</p>
<p>Dapper works as an extension of the IDbConnection interface through extension methods. With the use of generics it can return typed objects otherwise it returns dynamic objects.</p>
<p>I thought that perhaps a simple ORM like this is only targeted to a single provider, but of course it uses ADO.NET, so all providers supported there should work with Dapper. But as I understand it, you write raw SQL, so it doesn’t help you if you want to switch provider. But how often do you really do that? And it also means that you don’t have to learn a new language.</p>
<p>The goal has been to create a really fast and simple mapper, and according to their <a href="http://code.google.com/p/dapper-dot-net/" target="_blank">benchmarks</a>, they have succeeded to make it fast. I think I heard that stackoverflow first used Linq2sql and Dapper is 4 times faster than Linq2SQL and 13 times faster than Entity Framework for a SELECT statement with 500 rows to Poco’s in their <a href="http://code.google.com/p/dapper-dot-net/source/browse/Tests/PerformanceTests.cs" target="_blank">test case</a>.</p>
<p>Of course it has some limitations, for example it lacks a identity map, but I suppose it makes it a good fit when you use a <a href="http://en.wikipedia.org/wiki/Command-query_separation" target="_blank">CQRS</a> architecture and separate commands and queries?</p>
<p>I like the simplicity, and the speed, so I might try it for real some day.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/23/dapper-dot-net-aka-micro-orm/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to debug a short hang</title>
		<link>http://blog.jayway.com/2011/04/14/how-to-debug-a-short-hang/</link>
		<comments>http://blog.jayway.com/2011/04/14/how-to-debug-a-short-hang/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 13:23:34 +0000</pubDate>
		<dc:creator>Björn Carlsson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=7975</guid>
		<description><![CDATA[What can I do? When Bob the tester comes, and tells me that the client application sometimes hangs for about 30 seconds, when Bob is doing nothing. This client, and a hand full of other clients are connected to a system of connected servers. The problem could be a busy server or some internal client [...]]]></description>
			<content:encoded><![CDATA[<h2>What can I do?</h2>
<p>When Bob the tester comes, and tells me that the client application sometimes hangs for about 30 seconds, when Bob is doing nothing. This client, and a hand full of other clients are connected to a system of connected servers. The problem could be a busy server or some internal client problem. We have to find out what the client is doing when it get’s busy, for no good reason.</p>
<p>My first idea was that perhaps Bob could use the feature in the task manager in Vista and Windows 7, right click on a process and select Create Dump File.</p>
<h2>Automate it?</h2>
<p>It would of course be better if we could automate it, it’s not that easy to select a process, right click and choose the right item within 30 seconds.</p>
<p>So then I found a good tool for generating dump files when a windows application is none responsive.</p>
<p>The tool is <a href="http://technet.microsoft.com/en-us/sysinternals/dd996900.aspx">ProcDump</a> from SysInternals.</p>
<p>ProcDump is a command-line utility whose primary purpose is monitoring an application for CPU spikes and generating crash dumps during a spike that an administrator or developer can use to determine the cause of the spike. ProcDump also includes hung window monitoring (<strong>using the same definition of a window hang that Windows and Task Manager use</strong>), unhandled exception monitoring and can generate dumps based on the values of system performance counters.</p>
<p>I have used it to catch the cases where TheClient hangs for a number of seconds.</p>
<p>To use it in this case:</p>
<ol>
<li>Start TheClient</li>
<li>Run ProcDump with the following command line:</li>
</ol>
<p>"procdump.exe -h -ma TheClient.exe TheClient.hang.dmp"</p>
<p>It will then generate a dump file in the current directory when the application shows as "Not responding". Then it’s just to bring out WinDbg to find out what was going on.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/04/14/how-to-debug-a-short-hang/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Automated Testing is Like Optimizing</title>
		<link>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/</link>
		<comments>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 09:57:17 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=6982</guid>
		<description><![CDATA[I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a [...]]]></description>
			<content:encoded><![CDATA[<p>I have my roots in the Atari demo scene, so I know the joys of optimizing the inner-loop of a software texture mapper down to the last assembly instruction. The bragging rights of knowing that not a single clock cycle is wasted. I am also grown up enough to know that this is not a skill many needs to practice. In fact going about in this way on a customers project would be fraudulent, even if I could dazzle them with how cool optimizing for branch predictions is.</p>
<p>I can understand the joys of making sure that every potential bug is removed, and the bragging rights of 100% automated test coverage as well. But I would argue that it is equally fraudulent to claim 100% automated test coverage to a client as a virtue. I am not arguing that automated tests should be abandoned, far from it. I am arguing that automated tests should be applied with the same care as optimizations. </p>
<h2>Premature Automated Testing is Bad</h2>
<p>We have all learned that premature optimizations are bad. Guessing what could fail is hard, the only safe route would be to write a check for everything! There is even a coding practice encouraging this, test driven development or TDD for short. Which should really be called ADD for assertion driven development. Since what is done is not testing, but checking by asserting conditions against a specification.</p>
<p>Take a moment and answer honestly; for any project with good automated test coverage what is the ratio between time spent writing the checks versus the time these checks have saved you? In my experience the more zealously automated test coverage is applied, the more time is spent maintaining the tests. For any project where automated tests have been written first, and code later, I have yet never experienced that the checks have saved more time than the time they cost to develop and maintain.</p>
<p>When optimizing it is hard to find the bottlenecks. Gut feeling is good many times, but often even your gut feeling is wrong and the performance bottle neck is somewhere you would never expect. It is the same with defects in code, your gut feeling is good for pin-pointing many defects, but often the cause is something you never expected. So instead of wasting time guessing what the problems may be down the road you should inspect and measure where the issues are. And when an issue is found then you write a check for it to ensure it does not break again.</p>
<h2>Change the Algorithm</h2>
<p>The best optimization is often not to optimize at all, but to change to a better algorithm. Writing a bubble sort algorithm in assembly will never yield a better result than a sloppy merge sort written in C anyway, so do not waste your time.</p>
<p>Same can be said about code quality. If you have many issues, and your code breaks often, adding automated tests will only be bandaid until it breaks the next time. Change the code into something more stable. If needed, write checks to ensure the new implementation conforms to the same public API when you refactor it. Take notice to write checks with as good coverage as needed when you are about to refactor your code not before.</p>
<p>If you architect your application with many small independent units, each with a clearly defined public API, then refactoring is not a big problem.</p>
<h2>Perceived Quality</h2>
<p>All green lights and a 100% automated test coverage looks good on a report. But it can never catch what is most important of all; is the application valuable to the user? In that regard the 100% automated test coverage is a false safety, it gives the illusion of quality. A dangerous illusion that can be used to blind managers, customers and other stakeholders from seeing the real issues with the application.</p>
<p>There is yet no testing framework made that is as efficient as a human being actually using the application. Not just people blindly following a test protocol, that is even worse. But stake holders using the application as intended. Not just short burst before committing code to source control, but also regularly on longer sessions. So that you get a feel for how the app is used, what works, or just what grinds your gears. Usability issues are also issues and should be dealt with.</p>
<p>Not every issue is created equal. With the limited time every project have fixing, or predicting, each and every one of them is never feasible. So do not waste time fixing the one in a million issue, or writing checks for the bread and butter code. But do make sure the application fails gracefully. Fail as gracefully as you can for the end-user, they are very forgiving if you fail with style and make sure no data is lost. But also fail gracefully for yourself, be generous with logging when you do fail. And remember to add an automated check so that the reason for the failure may never raise again, once you fixed it.</p>
<h2>Model View Controller</h2>
<p>All application logic can be divided into three categories. Model for the business logic of your product, View for the display and input to and from the user (or other application), and Controller that is the mediator between the two. Any application of any significant size will have smaller MVC patterns within their units as well. Well defined boundaries between what is a Model, View and Controller is not only good for re-usability, maintainability, and replacing parts. It is also great for testing. Have well defined and testable public APIs for the parts, and the private implementations tend to be simpler and of higher quality. Do not let the public API be defined by how something is implemented, let the implementation be defined by how you want to access it from the outside. </p>
<p>Writing unit tests for the Model of your application is seldom a waste of time. Often the Model is what you begin implementing, so using unit tests as the incubator until you have enough logic in place to implement the first draft of your application is only rational; code that is unused is seldom of any quality at all.</p>
<p>Writing unit tests for the View yield much less returns on investment. It is also highly probably that you will have to write these tests over and over again. I would go so far as call them harmful, too many automated tests on the Views may in fact discourage you from doing drastic but needed usability changes. And no automated test in the world can ever flag if a View is usable, looks good, and feels right to the end-user.</p>
<p>Writing unit tests for the Controller should be a waste of time, otherwise your Controller is doing too much. A Controller should only be the mediator between the View and Model, if it does more then it should be split up and the proper parts moved into Model and View layers. So writing unit tests for a good Controller is basically just verifying that your are using the APIs of the Model and Views correctly. </p>
<h2>Conclusions</h2>
<p>We have learned that premature optimization is bad, often counter productive or wastes our time for minimal gains. Let us all grow up and also learn that premature automated testing is equally bad. The time we have is to precious to waste on overzealous automated testing instead of adding real value to the product by applying tests where it makes real difference to the products quality.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/01/07/automated-testing-is-like-optimizing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Developing JMeter plugins using Maven</title>
		<link>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/</link>
		<comments>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 15:44:22 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[jmeter]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5814</guid>
		<description><![CDATA[I have been using JMeter for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as Nexus. ]]></description>
			<content:encoded><![CDATA[<p>I have been using <a href="http://jakarta.apache.org/jmeter/">JMeter</a> for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as <a href="http://nexus.sonatype.org/">Nexus</a>. </p>
<h3>Building the plugin</h3>
<p>Building a plugin using maven is easy, simply add the following to your pom:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>installation directory of jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-core<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/ext/ApacheJMeter_core.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-jorphan<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/jorphan.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>You probably want to put <code>jmeter.home</code> in your <code>settings.xml</code> instead.</p>
<h3>Testing the plugin</h3>
<p>Whenever I develop something I want to have a quick build/test cycle. In this case I want to to start the JMeter UI without having to update the JMeter installation or any other manual work. I didn't get <a href="http://mojo.codehaus.org/chronos-maven-plugin/">chronos</a> to add my plugin to the UI. It seems chronos copied the jar files to <code>JMETER_HOME/lib/junit</code> and this probably works for running an already created test, but not for creating the test. I also failed to the the <a href="http://mojo.codehaus.org/exec-maven-plugin/index.html">maven exec plugin</a> to create the command line arguments I needed. Instead I added a small ant script to start JMeter:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>maven-antrun-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tasks<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;runtime_classpath&quot;</span>
           <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;maven.runtime.classpath&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;exec</span> <span style="color: #000066;">executable</span>=<span style="color: #ff0000;">&quot;${jmeter.home}/bin/jmeter.bat&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;arg</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;-Jsearch_paths=${runtime_classpath}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/exec<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/tasks<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/build<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>To run the jmeter gui simply run <code>mvn antrun:run</code>. This only works for Windows, I leave other platforms as an exercise to the reader <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<h3>Using the plugin</h3>
<p>I ended up copying the plugin jar and dependencies to the JMeter installation and used then this modified JMeter distribution when performing the tests. The reason was that I didn't have maven installed on some of the test clients. To copy dependencies you can use <a href="http://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html">mvn dependency:copy-dependencies</a>.<br />
If you want to run JMeter using maven you probably want to look at <a href="http://mojo.codehaus.org/chronos-maven-plugin/index.html">chronos</a> (although it is not released it seems to work fine):</p>
<ul><a href="http://gabenell.blogspot.com/2009/11/using-maven-chronos-without-external.html">Using Maven Chronos Without an External JMeter Install</a></ul>
<ul><a href="http://blogs.atlassian.com/developer/2009/10/automated_performance_testing_using_jmeter_and_maven.html">Automated performance testing using JMeter and Maven</a></ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance nightmare</title>
		<link>http://blog.jayway.com/2010/03/05/performance-nightmare/</link>
		<comments>http://blog.jayway.com/2010/03/05/performance-nightmare/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 06:52:17 +0000</pubDate>
		<dc:creator>Björn Carlsson</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4810</guid>
		<description><![CDATA[22 to 0.3 seconds! I found a simple solution to a very common problem. While profiling I found that remove in this little method took a lot of the time. public void MovePropertyFirst(IProperty property) { properties.Remove(property); properties.Insert(0, property); } The reason was, that it's time consuming to compare the properties by equality, for complex types. [...]]]></description>
			<content:encoded><![CDATA[<p>22 to 0.3 seconds!</p>
<p>I found a simple solution to a very common problem. While profiling I found that remove in this little method took a lot of the time.</p>
<pre>   public void MovePropertyFirst(IProperty property)
   {
      properties.Remove(property);
      properties.Insert(0, property);
   }</pre>
<p>The reason was, that it's time consuming to compare the properties by equality, for complex types. I think that in most (?) cases we want to delete the very same instance we supply as parameter to the remove method.</p>
<p>So I implemented a ReferenceEquals based remove, and by that I cut the time spent in remove by about 72 times!</p>
<pre>  public static bool RemoveFrom&lt;T&gt;(this IList&lt;T&gt; list, T itemToRemove)
  {
    if(list.Count == 0)
      return false;
    int index = 0;
    foreach (var item in list)
    {
      if (ReferenceEquals(item, itemToRemove))
      {
        list.RemoveAt(index);
        return true;
      }
      index++;
    }
    Debug.Assert(false, "Item to delete not found");
    //equality based fall back
    return list.Remove(itemToRemove);
  }</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/05/performance-nightmare/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Learn to Stop Worrying and Love the Singleton</title>
		<link>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/</link>
		<comments>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 13:00:10 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[spring ldap]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4273</guid>
		<description><![CDATA[Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. [...]]]></description>
			<content:encoded><![CDATA[<p>Enterprise applications and mobile applications have quite different requirements. Starting an enterprise application is just something you do once before it continue running for months or years. On the other side of the spectrum most mobile applications seldom runs for more than minutes, run by a bored users standing in line or riding the bus. This means that a mobile application must start in an instant, whereas starting and enterprise application may take as long as it takes. </p>
<p>Dependency injection and early validation is crucial for an enterprise application, and <a href="http://www.springsource.org/">Spring</a> is a boon in this regard. But do not fool yourself, Spring is good, but it is not a universal cure. Especially not in mobile space where startup times, low memory consumption, and avoiding interfaces are virtues.</p>
<p>The bottleneck in an enterprise application is most probably the database, spending a few extra milliseconds here and there seldom matters. On much less performant mobile device those clock cycles are not only time the user has to spend waiting, it will drain the battery. A simple thing as using an interface instead of an abstract superclass will perform at least twice as slow. Even passing an extra argument in the constructors a few nestings deep will have an impact.</p>
<h3>Lazy Singeltons by Choice</h3>
<p>Class loading in Java is lazy, the Java VM will not load classes until they are referenced. Odds are that the user will not trigger a full coverage of all classes in your app for a short time running mobile app. If the user just checks for incoming messages and quits, then every class involved in composing messages do not need to be loaded. Early dependency injection breaks this, as all classes will be referenced at startup. Most components will be initialized in vain, as they are never actually used.</p>
<p>So what we should do in mobile application is to work more like the Java VM, and less like Spring. If possible do not create a component until it is requested. The best way to do this is using a singleton pattern. Not a normal enforced singleton pattern, but rather a singleton by choice. Let the constructor be public, trust your users, and name the getter <code>getSharedFoo()</code>, not <code>getInstance()</code>. Let me show you using a example of an URL cache component:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  public URLCache() {
    // More code...
  }
  // Allot more code here...

}</pre>
<p>Using this shared URL cache component from our imaginary HTTP provider would then be super easy, but not mandatory:</p>
<pre class="brush:java">public class HTTPProvider {

  public InputStream inputStreamForURL(String url) {
    URLCache cache = URLCache.getSharedURLCache();
    // Use the cache...
  }

}</pre>
<p>The big win here is that if the code path of this run of the application never tries to open an input stream then the URL cache never has to be created. Saving several hundred milliseconds of reading cache indexes, validation, etc.</p>
<h3>But What About Testing?</h3>
<p>Are not singletons bad for unit tests and mocking components? They used to be. These days we have <a href="http://www.powermock.org/">PowerMock</a>, you really should use it. Turns out that not even PowerMock is really required, if we just change our singleton pattern very slightly, and allows the outside to set the shared component as well:</p>
<pre class="brush:java">public class URLCache {
  private static URLCache sharedCache;

  public static void setSharedURLCache(URLCache cache) {
    synchronized (URLCache.class) {
      sharedCache = cache;
    }
  }

  public static URLCache getSharedURLCache() {
    synchronized (URLCache.class) {
      if (sharedCache == null) {
        sharedCache = new URLCache();
      }
    }
    return sharedCache;
  }

  // Allot more code here...

}</pre>
<p>This small addition allows us for setup up our own mock cache in the setup of our unit tests. With something as simple as this:</p>
<pre class="brush:java">public class SomeTest extends TestCase {

  public void setUp() {
    URLCache.setSharedURLCache(new NoOpURLCache());
  }

  public void testRemoteResource() {
    assertNotNull(HTTPProvider.getSharedHTTPProvider().inputStreamForURL(TEST_URL));
  }
}</pre>
<p>It also allows us for explicitly override a singleton if our application has special needs, perhaps a more aggressive cache on a low bandwidth mobile data connection, or special implementation on a buggy Java ME platform. But most importantly for the normal case it will not waste time creating the component until it is actually needed, vastly improving the user experience for your mobile users.</p>
<h3>Take Aways</h3>
<p>Do not fear singletons, it is a great way of lazy creations that will greatly improve startup times and memory consumption on mobile applications.</p>
<p>Avoid using interfaces, they are at least twice as slow as classes, and can not have static methods for acquiring the lazy created components.</p>
<p>Do not enforce the singleton pattern, always use singleton by choice. To allow for testing and easy implementation of special cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/learn-to-stop-worrying-and-love-the-singleton/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Queued Background Tasks for Cocoa</title>
		<link>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/#comments</comments>
		<pubDate>Sat, 09 May 2009 12:42:04 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1665</guid>
		<description><![CDATA[The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource [...]]]></description>
			<content:encoded><![CDATA[<p>The megahertz race is over, and instead we get more execution cores. This means that we as developers must make our applications parallel, in order to take advantage of the new performance. The easiest way to be parallel is to execute tasks in new threads, something that is useful also for lengthy but not resource intensive tasks such as network access.</p>
<p>Any sane developer avoids premature optimization, so the task we later want to execute in a separate thread is almost always available in our current context. I am sure all Java-developers has seen something like this:</p>
<pre class="java"> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThread+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Thread</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> run<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        OuterClass.<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">someMethod</span><span style="color: #66cc66;">&#40;</span>arg<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>.<span style="color: #006600;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre>
<p>And often an anonymous <code>Runnable</code> is involved as well. Executing a task in a separate thread with Cocoa and Cocoa Touch is ridiculously easy given the dynamic nature of Objective-C. This is done with Cocoa with this one-liner:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorInBackground:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>The <code>performSelectorInBackground:withObject:</code> is a companion method for <code>performSelector:withObject:</code>, and will create a new <code>NSThread</code> instance, and execute the specified method there. There are more companions such as <code>performSelectorOnMainThread:withObject:</code> that is used to execute a method on the main UI thread.</p>
<p>This easy access to executing in new threads often can result in code that spawns too many threads. In Cocoa on Mac OS X this is seldom a problem, not for Cocoa Touch applications under development when running in the iPhone simulator either. But on the more resource constrained iPhone and iPod Touch devices this will be a problem. Spawning a dozen background threads to download images will bring the iPhone OS to a staggering mess.</p>
<p><em><strong>Update: </strong>I have removed <code>CWSelectorOperation</code> from this post, since using <code>NSInvocationOperation</code> is preferred.</em></p>
<h3>Operation Queues</h3>
<p>The solution is to use a <code>NSOperationQueue</code>, that as the name implies handles a queue of operations. The max number of concurrent operations can be set, as well as dependencies and priority. The downside is that <code>NSOperationQueue</code> can only handle instances of <code>NSOperation</code>.</p>
<p><code>NSOperation</code> is an abstract class, where you as a developer override the <code>main</code> method to execute your task. In short <code>NSOperation</code> is programatically the equivalent of the Java <code>Runnable</code> interface. It is even worse as Objective-C do not support anonymous classes, so we will be required to actually implement our queued tasks as separate classes.</p>
<p>Not as neat as one would like, and definitely not even very Cocoa-like.</p>
<h3>What is Missing</h3>
<p>As a Cocoa developer I expect that executing a task on background queue, would be just as easy as executing a task on a background thread. The expected needed code is something like this:</p>
<pre class="objc"><span style="color: #002200;">&#91;</span>self performSelectorOnBackgroundQueue:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>someMethod:<span style="color: #002200;">&#41;</span> withObject:arg<span style="color: #002200;">&#93;</span>;</pre>
<p>To make this work we need:</p>
<ol>
<li>A category on <code>NSObject</code> to add <code>performSelectorOnBackgroundQueue:withObject:</code>.</li>
<li><del datetime="2009-05-13T10:47:35+00:00">Implement a concrete subclass of <code>NSOperation</code> to support execution of a selector on any target.</del>Use <code>NSInvocationOperation</code> to perform selector.</li>
<li>A category on <code>NSOperationQueue</code> to add a shared operation queue.</li>
</ol>
<p>This is in the order of how a client developer would see it (most developers will only care for the <code>NSObject</code> category). For us this is the reverse order when implement this functionality.</p>
<h3>A Shared Operation Queue</h3>
<p>Cocoa and Cocoa Touch used many shared instances, for example a shared <code>UIAccelerometer</code> instance, and a shared <code>NSURLCache</code> instance. So this pattern of single point dependency injection is common in Cocoa and works very well. So let us follow suit by introducing an interface like this:</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #0000ff;">@end</span></pre>
<p>The shared operation queue will be created lazily if it do not exist, and the client can easily swap it out at startup if needed. The implementation is very small, and a good example of how we should implement class variables with proper memory handling.</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> NSOperationQueue <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
<span style="color: #0000ff;">static</span> NSOperationQueue* cw_sharedOperationQueue = <span style="color: #0000ff;">nil</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>sharedOperationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>cw_sharedOperationQueue == <span style="color: #0000ff;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue setMaxConcurrentOperationCount:<span style="color: #0000dd;">3</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> cw_sharedOperationQueue;
<span style="color: #002200;">&#125;</span>
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>setSharedOperationQueue:<span style="color: #002200;">&#40;</span>NSOperationQueue*<span style="color: #002200;">&#41;</span>operationQueue;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>operationQueue != cw_sharedOperationQueue<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>cw_sharedOperationQueue release<span style="color: #002200;">&#93;</span>;
    cw_sharedOperationQueue = <span style="color: #002200;">&#91;</span>operationQueue retain<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3><del datetime="2009-05-13T10:47:35+00:00">Enter <code>CWSelectorOperation</code></del></h3>
<p><em><strong>Update: </strong><code>CWSelectorOperation</code> is no longer needed, our implementation instead uses <code>NSInvocationOperation</code>.</em></p>
<h3>Wrapping up <code>NSObject</code></h3>
<p>And at last we reach the category on <code>NSObject</code>, that is what we initially wanted, and what 95% of all use cases will be limited to.</p>
<pre class="objc"><span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>Most <code>performSelector*</code> methods do not have a return value, I have chosen to return the resulting <code> NSInvocationOperation </code> so that it can be used to setup dependencies for future queued operations. I have also added a second method <code>performSelectorInBackgroundQueue:withObject:dependencies:priority:</code> so that such dependencies can easily be setup, as well as prioritisation of operations.</p>
<p>The actual implementation is a simple wrapper around the <code> NSInvocationOperation </code> class, and category on <code>NSOperationQueue</code> that we implemented above:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSObject.html"><span style="color: #0000ff;">NSObject</span></a> <span style="color: #002200;">&#40;</span>CWSharedQueue<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSInvocationOperation*<span style="color: #002200;">&#41;</span>performSelectorInBackgroundQueue:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector
    withObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>arg dependencies:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>dependencies
    priority:<span style="color: #002200;">&#40;</span>NSOperationQueuePriority<span style="color: #002200;">&#41;</span>priority;
<span style="color: #002200;">&#123;</span>
  NSInvocationOperation* operation = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSInvocationOperation alloc<span style="color: #002200;">&#93;</span>
      initWithTarget:self selector:aSelector object:arg<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>operation setQueuePriority:priority<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span>NSOperation* dependency in dependencies<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>operation addDependency:dependency<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>NSOperationQueue sharedOperationQueue<span style="color: #002200;">&#93;</span> addOperation:operation<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>operation autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>And that is it, if you want to avoid cut and paste of all this code to your own project just <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/nsoperationqueuecwsharedqueue.zip'>download the source code here</a>. And happy concurrent hacking.</p>
<p>Download the <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/05/cwselectoroperation.zip'>older source code here</a>, with a concrete subclass of <code>NSOperation</code> called <code>CWSelectorOperation</code>. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/09/queued-background-tasks-for-cocoa/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Regular Expressions and Cocoa</title>
		<link>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/</link>
		<comments>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/#comments</comments>
		<pubDate>Wed, 06 May 2009 19:36:27 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://79.125.9.149/?p=1617</guid>
		<description><![CDATA[Regular expressions is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Regular_expression">Regular expressions</a> is a powerful tool for solving many problems related to text. It can be misused as any good tool, but there are moments when they are the best solution for a given problem. At those moments the lack of regular expressions for Cocoa on Mac OS X and Cocoa Touch on iPhone OS is a pain in the butt.</p>
<p>Or are regular expressions really missing? Regular expressions can be used with <code>NSPredicate</code> that is part of Core Data, available since Mac OS X 10.4 and officially announced for iPhone OS 3.0. Cocoa's <code>WebView</code> and the equivalent <code>UIWebView</code> in Cocoa Touch both support JavaScript with regular expressions. So there sure is regular expressions available on the platforms, but how do you make it available for your own code?</p>
<h3>An Ugly Solution</h3>
<p>You can actually get access to the regular expression engine through JavaScript, unfortunately this requires a roundtrip through <a href="http://webkit.org/">WebKit</a>. On an iPhone this means you have to use an off-screen instance of <code>UIWebView</code>, and delegate execution of regular expression to it. </p>
<p>The complexity of an off-screen <code>WebView</code> or <code>UIWebView</code> could be hidden by a utility class. But the extra glue code needed to make something useful out of the single method <code>stringByEvaluatingJavaScripFromString:</code>, would be allot.</p>
<h3>What Apple Recommends</h3>
<p>For most problems the official stance is correct; do not use regular expressions. Instead use <code>NSScanner</code>, that is perfect for sequentially parse texts. It is very fast and can substitute any regular expressions that only relies on:
<ul>
<li>Character sets</li>
<li>Exact string matches</li>
<li>Numerical matches</li>
<li>Uniform input text</li>
</ul>
<p>These conditions hold true to 95% of everything regular expressions is ever used for. For the other 5%, Apple leaves you to fend for your own.</p>
<h3>Other Solutions</h3>
<p><a href="http://www.pcre.org/">PCRE</a> compiles perfectly with Cocoa, since it is written in C, one of the many advantages of Objective-C. PCRE is very capable, and almost a standard, but also very large. For an iPhone application the PCRE implementation could end up as the majority of your executables file-size. If this is something you can live with, then the open source <a href="http://regexkit.sourceforge.net/">RegexKit</a> framework wraps PCRE in Cocoa and Cocoa Touch friendly Objective-C.</p>
<p>Another regular expressions framework is <a href="http://www8.ocn.ne.jp/~sonoisa/OgreKit/">OgreKit</a>. The advantage of OgreKit is full unicode support, with the same disadvantage of size. And the fact that the documentation is in Japanese.</p>
<h3>A Pretty Solution</h3>
<p>It turns out that Mac OS X for years, and iPhone OS since inception, has been shipped with a perfectly good regular expressions engine. This engine is based on the <a href="http://site.icu-project.org/">ICU specification</a>, so it works perfectly with unicode and is well on par with PCRE for functionality. This framework is simply called ICU Core, and has a C interface. But for a Cocoa programmers the C interface is not nice enough, and thankfully <a href="http://twitter.com/johnengelhart">John Engelhart</a> has done this work for us, with <a href="http://regexkit.sourceforge.net/RegexKitLite/">RegexKitLite</a>. RegexKitLite is a little brother to RegexKit that wrapps ICU Core instead of PCRE.</p>
<p>RegexKitLite is published under <a href="http://en.wikipedia.org/wiki/BSD_license">BSD license</a>, and is simply two files you add to your project, fully compatible with all available versions of both Mac OS X and iPhone OS. The tricky part is that ICU Core is not a public API officially supported by Apple, even though it has existed unchanged for years. Good news is that using ICU Core is not a show stopper for publishing on the iPhone App Store, application out there already uses it, both <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284540316&mt=8">well known</a> and <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=305963116&mt=8">not so well known</a>.</p>
<h3>Setting Up RegexKitLite</h3>
<ol>
<li>Download the latest version from the <a href="http://sourceforge.net/project/showfiles.php?group_id=204582&package_id=268643">sourceforge webpage</a>, or <a href="http://sourceforge.net/scm/?type=svn&group_id=204582">SVN</a>.</li>
<li>Add <code>RegexKitLite.h</code> and <code>RegexKitLite.m</code> to your project.</li>
<li>Link your project against ICU Core, by adding the linker flag <code>-licucore</code> to <em>Other Linker Flags</em> under your projects build settings.</li>
</ol>
<p>Optionally you can also add the documentation to Xcode with these easy steps:</p>
<ol>
<li>Open <em>Help -> Documtantion</em>.</li>
<li>Press the Gears button in the lower left corder, and select <em>New Subscription...</em>.</li>
<li>Enter <code>feed://regexkit.sourceforge.net/RegexKitLiteDocSets.atom</code> as URL.</li>
</ol>
<h3>Using RegexKitLite</h3>
<p>This post is not a tutorial on regular expressions, but a tutorial on a partical API for executing regular expressions. If you want to learn more about regular expressions themselves I would recomend you look at <a href="http://www.regular-expressions.info">Regular Expressions.info</a>.</p>
<p>RegexKitLite provides it's functionality as categories on <code>NSString</code> and <code>NSMutableString</code>. This way using regular expressions with Cocoa is just as easy and normal string manipulation. This is best described using examples.</p>
<p>A simple example that normalizes a text with single white spaces, kind of like how a HML renderer would do, so this is handy when scraping web pages:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;One<span style="color: #666666; font-weight: bold;">\t</span> Two <span style="color: #666666; font-weight: bold;">\n</span>Three &quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* result = <span style="color: #002200;">&#91;</span>source stringByReplacingOccurancesOfRegex:@<span style="color: #666666;">&quot;<span style="color: #666666; font-weight: bold;">\\</span>s+&quot;</span>
    withString:@<span style="color: #666666;">&quot; &quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>source<span style="color: #002200;">&#41;</span>;
NSLog<span style="color: #002200;">&#40;</span>result<span style="color: #002200;">&#41;</span>;</pre>
<p>Or you can split a text, such as semi-colon delimeted data:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;Test;12;Y&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>* columns = <span style="color: #002200;">&#91;</span>source componentsSeparatedByRegex:@<span style="color: #666666;">&quot;;<span style="color: #666666; font-weight: bold;">\\</span>s*&quot;</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>columns description<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre>
<p>And you can extract more complex data using capture groups:</p>
<pre class="objc"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* source = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>12<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;Name&lt;/foo&gt;&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* regex = @<span style="color: #666666;">&quot;&lt;foo no=<span style="color: #666666; font-weight: bold;">\&quot;</span>(.+?)<span style="color: #666666; font-weight: bold;">\&quot;</span>&gt;(.*?)&lt;/foo&gt;&quot;</span>;
<span style="color: #0000ff;">int</span> no = <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">1</span><span style="color: #002200;">&#93;</span> intValue<span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSString.html"><span style="color: #0000ff;">NSString</span></a>* data = <span style="color: #002200;">&#91;</span>source stringByMatching:regex capture:<span style="color: #0000dd;">2</span><span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span>@<span style="color: #666666;">&quot;no: %d data: %@&quot;</span>, no, data<span style="color: #002200;">&#41;</span>;</pre>
<p>This may look like it could be slow to perform matches on the same regular expression twice, but it is not. RegexKitLite is very smart, and will cache your previous matches for very high performance.</p>
<p>RegexKitLite is a very capable, and also much active open source project, with version 3.0 as a release candidate in SVN. Use it, and use it well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/06/regular-expressions-and-cocoa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding Sorted Inserts to Cocoa Arrays</title>
		<link>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/</link>
		<comments>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 22:39:22 +0000</pubDate>
		<dc:creator>Fredrik Olsson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1441</guid>
		<description><![CDATA[NSArray and NSMutableArray have methods for sorting arrays, NSArray returns new sorted arrays and NSMutableArray can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of NSSortDescriptor objects. NSArray admits to sorts being a slow operation, and adds a method pair for comultive [...]]]></description>
			<content:encoded><![CDATA[<p><code>NSArray</code> and <code>NSMutableArray</code> have methods for sorting arrays, <code>NSArray</code> returns new sorted arrays and <code>NSMutableArray</code> can be sorted in place. The sort methods comes in three flavours; using a function, using a selector, or using an array of <code>NSSortDescriptor</code> objects.</p>
<p><code>NSArray</code> admits to sorts being a slow operation, and adds a method pair for comultive sorts using hints. This way the operation is done in <em>O(P*LOG(P)+N)</em> time, instead of <em>O(N*LOG(N))</em>. Where <em>N</em> is number of elements, and <em>P</em> is number of additions and deletions since the last sort. Unfortunately that do not work on <code>NSMutableArray</code>. So even if memory consumption will not hit the roof, release retain cycles will take it's toll.</p>
<p>So why not add methods to find the insertion points, and insert new objects into already sorted <code>NSArray</code> and <code>NSMutableArray</code> object? Best case for inserting single elements should be <em>O(LOG(N)^2)</em>, so lets hit that target. And on the way there, we will learn how to;
<ul>
<li>Add functionality to standard classes using categories.</li>
<li>Implement high performant Obj-C code for tight loops.</li>
</ul>
<h3>New Categories on <code>NSArray</code> and <code>NSMutableArray</code></h3>
<p>This will become a bit complex on the inside, but the public front should be as simple as this:</p>
<pre class="objc"><span style="color: #339900;">#import &lt;Foundation/Foundation.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span>
&nbsp;
<span style="color: #0000ff;">@interface</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Base Implementation</h3>
<p>We want to follow suit with <code>NSArray</code> and <code>NSMutableArray</code>, so we too shall support inserts based on functions, selectors, and an array of sort descriptors. In practice we only need to implement <code>indexForInsertingObject:sortedUsingfunction:context:</code>, the other methods can use this one, each with a private compare method of their own. So we begin by implementing this method.</p>
<pre class="objc"><span style="color: #339900;">#import &quot;NSArray+CWSortedInsert.h&quot;</span>
<span style="color: #339900;">#import &lt;objc/runtime.h&gt;</span>
&nbsp;
<span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #0000dd;">0</span>;
  NSUInteger topIndex = <span style="color: #002200;">&#91;</span>self count<span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">IMP</span> objectAtIndexImp = <span style="color: #002200;">&#91;</span>self methodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #0000ff;">while</span> <span style="color: #002200;">&#40;</span>index &lt; topIndex<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSUInteger midIndex = <span style="color: #002200;">&#40;</span>index + topIndex<span style="color: #002200;">&#41;</span> / <span style="color: #0000dd;">2</span>;
    <span style="color: #0000ff;">id</span> testObject = objectAtIndexImp<span style="color: #002200;">&#40;</span>self, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>objectAtIndex:<span style="color: #002200;">&#41;</span>, midIndex<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>compare<span style="color: #002200;">&#40;</span>anObject, testObject, context<span style="color: #002200;">&#41;</span> &lt; <span style="color: #0000dd;">0</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      index = midIndex + <span style="color: #0000dd;">1</span>;
    <span style="color: #002200;">&#125;</span> <span style="color: #0000ff;">else</span> <span style="color: #002200;">&#123;</span>
      topIndex = midIndex;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> index;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<p>The Objective-C runtime header <code><objc/runtime.h></code> is included so we can go around the usual method dispatch, and instead use the method implementations as function pointers. In most cases this is a neglectable optimization, for this case we will be the bottle neck since we are intended to be the low level API.</p>
<p>The algorithm is a simple binary search, and we have a worst case <em>O(LOG(N)^2)</em> time for index search. Using this for implementing the sibling method in <code>NSMutableArray</code> is as simple as this:</p>
<pre class="objc"><span style="color: #0000ff;">@implementation</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSMutableArray.html"><span style="color: #0000ff;">NSMutableArray</span></a> <span style="color: #002200;">&#40;</span>CWSortedInsert<span style="color: #002200;">&#41;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>insertObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingfunction:<span style="color: #002200;">&#40;</span>NSInteger <span style="color: #002200;">&#40;</span>*<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">id</span>, <span style="color: #0000ff;">void</span> *<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>compare
    context:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span>*<span style="color: #002200;">&#41;</span>context;
<span style="color: #002200;">&#123;</span>
  NSUInteger index = <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:compare context:context<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self insertObject:anObject atIndex:index<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #ff0000;">// More code here...</span>
&nbsp;
<span style="color: #0000ff;">@end</span></pre>
<h3>Sort Using Selector</h3>
<p>With functions in place, writing a utility compare function that uses selectors, and can be used with our <code>indexForInsertingObject:sortedUsingfunction:context:</code> method is a breeze.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_SelectorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* aSelector<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>objc_msgSend<span style="color: #002200;">&#40;</span>a, <span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector, b<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingSelector:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">SEL</span><span style="color: #002200;">&#41;</span>aSelector;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_SelectorCompare context:aSelector<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>Notice that <code>objc_msgSend(id, SEL, ...)</code> is used instead of the <code>performSelector:withObject:</code> method. This is a small performance improvement, as what <code>performSelector:withObject:</code> do behind the scene is just a call to <code>objc_msgSend()</code> anyway. We have removed one method invokation per compare.</p>
<h3>Sort Using Sort Descriptors</h3>
<p>Or rather sort with an array or <code>NSSortDescriptor</code> objects. This will be the least performant, but also the most flexible sort. An array of sort descriptors is used because we want to be able to sort using several criteria, one sort descriptor per criteria. For example when sorting on last name, then first name, or even more complex sorts.</p>
<p>A <code>NSSortDescriptor</code> is initialized with a key, sort order (ascending or descending) and optionally a selector to do the comparison with, by default <code>compare:</code>. There are quite a few method invokations involved, and it will be good for performance to avoid as many as we can.</p>
<p>Just as <code>performSelector:withObject:</code> uses <code>objc_msgSend()</code> behind the scene, so do <code>objc_msgSend</code> use a function pointer internally. After doing a hash-table lookup with the selector as key that is. This look-up is cached and very fast, but avoiding it all together is always faster. So let us fetch those when the category is first loaded, and do our calls straight through the functions pointers avoiding at least two or more function calls for each compare operation.</p>
<pre class="objc"><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_compareObjectToObjectImp = <span style="color: #0000ff;">NULL</span>;
<span style="color: #0000ff;">static</span> <span style="color: #0000ff;">IMP</span> cw_ascendingImp = <span style="color: #0000ff;">NULL</span>;
&nbsp;
+<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">void</span><span style="color: #002200;">&#41;</span>initialize;
<span style="color: #002200;">&#123;</span>
  cw_compareObjectToObjectImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
  cw_ascendingImp = <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>
      instanceMethodForSelector:<span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<p>The class method <code>inilialize</code> is kind of magic, it is called once for each class and category, when the class or category is loaded into the run-time. It is the Obj-C equivalent of static initializers.</p>
<p>With the function pointers to the hot-spot method implementations in hand, here is the fast implementation:</p>
<pre class="objc"><span style="color: #0000ff;">static</span> NSComparisonResult cw_DescriptorCompare<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span> a, <span style="color: #0000ff;">id</span> b, <span style="color: #0000ff;">void</span>* descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSComparisonResult result = NSOrderedSame;
  <span style="color: #0000ff;">for</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSSortDescriptor.html"><span style="color: #0000ff;">NSSortDescriptor</span></a>* sortDescriptor in <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    result = <span style="color: #002200;">&#40;</span>NSComparisonResult<span style="color: #002200;">&#41;</span>cw_compareObjectToObjectImp<span style="color: #002200;">&#40;</span>sortDescriptor,
        <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>compareObject:toObject:<span style="color: #002200;">&#41;</span>, a, b<span style="color: #002200;">&#41;</span>;
    <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>result != NSOrderedSame<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      <span style="color: #0000ff;">if</span> <span style="color: #002200;">&#40;</span>!cw_ascendingImp<span style="color: #002200;">&#40;</span>sortDescriptor, <span style="color: #0000ff;">@selector</span><span style="color: #002200;">&#40;</span>ascending<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      	result = <span style="color: #0000dd;">0</span> - result;
      <span style="color: #002200;">&#125;</span>
      <span style="color: #0000ff;">break</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
  <span style="color: #0000ff;">return</span> result;
<span style="color: #002200;">&#125;</span>
&nbsp;
-<span style="color: #002200;">&#40;</span>NSUInteger<span style="color: #002200;">&#41;</span>indexForInsertingObject:<span style="color: #002200;">&#40;</span><span style="color: #0000ff;">id</span><span style="color: #002200;">&#41;</span>anObject
    sortedUsingDescriptors:<span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/ObjC_classic/Classes/NSArray.html"><span style="color: #0000ff;">NSArray</span></a>*<span style="color: #002200;">&#41;</span>descriptors;
<span style="color: #002200;">&#123;</span>
  <span style="color: #0000ff;">return</span> <span style="color: #002200;">&#91;</span>self indexForInsertingObject:anObject
      sortedUsingfunction:&amp;cw_DescriptorCompare context:descriptors<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre>
<h3>Conclusions</h3>
<p>The fact that Objective-C is a strict superset of C have some good benefits. The obvious one is that your Obj-C code is both source-code and binary compatible with the vast collection of code that has been written in C over the past 30+ years.</p>
<p>The second benefit is that when performance is needed, Obj-C gives us as developers full access to the internals of the dynamic run-time.</p>
<p>But best of all, most developers never need to care. They can, blissfully unaware, reap the benefits of the performance tuning under the hood. Tuning by both Apple and considerate third party library developers willing to go the extra mile (or a few metres at least).</p>
<p>The code is released under BSD license, and works on both Mac OS X and iPhone OS. You can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/nsarraycwsortedinsert.zip'>download it here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/28/adding-sorted-inserts-to-uimutablearray/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Squid, the caching proxy</title>
		<link>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/</link>
		<comments>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/#comments</comments>
		<pubDate>Fri, 06 Jun 2008 18:37:34 +0000</pubDate>
		<dc:creator>Ulrik Sandberg</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=85</guid>
		<description><![CDATA[I just checked out the old Squid again, the worlds most famous caching proxy. If you direct all your web access through the Squid proxy server, it will cache stuff after the first access. This would simplify for example for labs where fifty people simultaneously begin retrieving stuff from a Maven repo somewhere or downloading [...]]]></description>
			<content:encoded><![CDATA[<p>I just checked out the old <a href="http://www.squid-cache.org/">Squid</a> again, the worlds most famous caching proxy. If you direct all your web access through the Squid proxy server, it will cache stuff after the first access. This would simplify for example for labs where fifty people simultaneously begin retrieving stuff from a Maven repo somewhere or downloading required libraries, and we have a very limited bandwidth.</p>
<p>On the Mac it was easy to get running (if you have <a href="http://www.macports.org/">MacPorts</a>):</p>
<pre>% sudo port install squid
% sudo squid -z (initialize stuff if you never ran Squid before)
% sudo squid -N -d 1 (no daemon, debug level 1)</pre>
<p>Then it was running on the console, and you could test it like this:</p>
<pre>% squidclient http://google.com
...
X-Cache: MISS from myhostname
Via: 1.0 myhostname:3128 (squid/2.7.STABLE2)</pre>
<p>And again, this time fetching from the cache:</p>
<pre>% squidclient http://google.com
...
X-Cache: HIT from myhostname
Via: 1.0 myhostname:3128 (squid/2.7.STABLE2)</pre>
<p>You configure your browser by simply setting proxy server to <code>localhost:3128</code>, if you are running your Squid locally, that is.</p>
<p>Maven is probably best configured in <code>~/.m2/settings.xml</code>:</p>
<pre>&lt;settings xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/xmlSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/xsd/settings-1.0.0.xsd"&gt;
  &lt;proxies&gt;
    &lt;proxy&gt;
      &lt;active&gt;true&lt;/active&gt;
      &lt;protocol&gt;http&lt;/protocol&gt;
      &lt;host&gt;localhost&lt;/host&gt;
      &lt;port&gt;3128&lt;/port&gt;
    &lt;/proxy&gt;
  &lt;/proxies&gt;
&lt;/settings&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/06/06/squid-the-caching-proxy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

