<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Marvellous Mechanical Mouse Organ &#187; Java</title>
	<atom:link href="http://fintanp.wordpress.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://fintanp.wordpress.com</link>
	<description>Start Braindump. Error: Brain not found.</description>
	<lastBuildDate>Thu, 15 Nov 2007 23:26:30 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='fintanp.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/29c36e7e4e2c551c9a59d0bc76a56d60?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>The Marvellous Mechanical Mouse Organ &#187; Java</title>
		<link>http://fintanp.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://fintanp.wordpress.com/osd.xml" title="The Marvellous Mechanical Mouse Organ" />
		<item>
		<title>Premature Optimization</title>
		<link>http://fintanp.wordpress.com/2007/03/15/premature-optimization/</link>
		<comments>http://fintanp.wordpress.com/2007/03/15/premature-optimization/#comments</comments>
		<pubDate>Thu, 15 Mar 2007 10:16:35 +0000</pubDate>
		<dc:creator>fintanp</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://fintanp.wordpress.com/2007/03/15/premature-optimization/</guid>
		<description><![CDATA[A former colleague of mine was recently trying to sort out a question in his head once and for all: which is better, declaring a variable inside a loop or outside of a loop? A Google search lead him to this thread on Javalobby and knowing my feelings on the subject he thought I’d find [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=34&subd=fintanp&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A former colleague of mine was recently trying to sort out a question in his head once and for all: which is better, declaring a variable inside a loop or outside of a loop? A Google search lead him to <a href="”http://www.javalobby.org/forums/thread.jspa?threadID=16730”">this thread on Javalobby</a> and knowing my feelings on the subject he thought I’d find the comments interesting. I certainly did but I wasn’t surprised by some of what I read.</p>
<p>It’s to be expected that most conscientious developers will have one eye on performance while writing their code. For example, in the Java world there are some obvious things you need to watch for to avoid unnecessary performance hits &#8211; using <em>StringBuilder</em> instead of <em>String</em> while building strings for instance or avoiding <em>Vector</em> when you don&#8217;t need thread safety. The real problem occurs when developers are tempted into doing little tricks that they think will improve the performance of their code when they don’t know where the real performance bottlenecks are in the first place. This is premature optimization and and like many things that are premature<sup>1</sup> it can cause embarrassment and quite a few problems.</p>
<p><span id="more-34"></span>The use of the keyword <em>final</em> in Java is a perfect example. You can use it, as it was intended, to explicitly seal the implementation of a class so that it cannot be sub-classed, or a method so that it cannot be overridden by a sub-class. You could also choose to use it to improve performance of method calls by removing them from the vtable. Think about what you are doing first though. Nothing you mark as final can be subclassed or overloaded. If you believe that code should be self-documenting then you are making a bold statement about its design. Regardless, you’re restricting the behaviour of those classes when other developers go to use them<sup>2</sup>. Is that what you want? Now think about the performance gain you’ve achieved. If you’re doing this before you’ve profiled the code to discover the real bottlenecks<sup>3</sup> it’s the coding equivalent of ordering four Big Macs, two large fries, an apple pie and a Diet Coke.</p>
<p>The question about whether or not to declare a variable inside or outside a loop can be sort of couched in the same terms. There are going to be times where if you are creating a new object instance it might be more efficient to do that outside a loop rather than inside but that is down to the cost of invoking the object’s constructor. If you’re just talking about declaring a variable which will have an object reference assigned to it then you’re asking the wrong questions about your code. The rule should always be to keep your code clean and simple and in this case a good general rule of thumb is to keep the usage scope of a variable as small as possible.</p>
<p>Instead of doing this<br />

<pre>
private void someMethod() {
    SomeObject blah;
    for (int i = 0; i &lt; 10; ++i) {
        blah = getBlah(i);
    }
}
</pre>
<p>you’re almost certainly much better off doing this<br />

<pre>
private void someMethod() {
    for (int i = 0; i &lt; 10; ++i) {
        SomeObject blah = getBlah(i);
    }
}
</pre>
<p>For starters there’s no chance that the object will get re-used out of context (accidentally or otherwise) thereby reducing the potential for any bugs. Secondly it makes refactoring much easier. If you decide later on to extract the contents of the loop as a method everything that is local to the scope of the loop should come out cleanly. The bottom line is that the code is cleaner and easier to maintain. That is usually half the battle when it comes to having performant code but notice that the two reasons I give for doing it this way, and there are others, aren&#8217;t explicitly about performance.</p>
<p>Feel free to get into arguments about what kind of bytecode is generated when you declare a variable inside or outside a loop <strong>after</strong> you have run a profiler to find where the real bottlenecks are and have eliminated them<sup>4</sup>. I can practically guarantee you that you won’t have to resort to any tricks to improve performance. Chances are the problems will be with some part of the implementation. You may be using the wrong collection types, using the wrong search algorithm, not pooling resources correctly etc. I would be really surprised if attempting to influence how quickly a method was being called or how long it was taking to declare a variable in a loop resulted in a significant performance improvement in your code.</p>
<p>The first question any developer should ask themselves when writing new code, after the obvious one of what should this code actually do, is how clean and simple is the design?  Inevitably a clean and simple design will be more efficient than a cluttered, trick-laden one.  Keep it simple, make it work and then make it fast. As with most things in this business, the 80/20 rule applies and you’ll probably find that 80% of the time taken will be spent in 20% of the code. Find that 20% and improve its performance and you’ll see real and meaningful gains in the overall performance of your code but concentrate first on writing clean, clear and simple code.</p>
<p>Writing “clean and simple” code can be a subjective exercise but there are things you can do to help the process. Over the next few weeks I’ll be posting a series of articles on how test-driven development and the new kid on the block, behaviour-driven development, can help you achieve this goal.</p>
<p>I will now put the soapbox away.</p>
<p>&#8211; Fintan</p>
<hr />1 &#8211; I just had to get a double-entendre in, didn’t I.<br />
2 &#8211;  I once saw this kind of “optimisation” performed on a bean-like class. I only found it when I was trying to figure out why an EasyMock-generated mock version of it wasn’t behaving as expected in a unit test.  Of course, because the methods were final they couldn’t be overridden and the mock object was being bypassed. I’m pretty sure that the performance gain was negligible.<br />
3 &#8211; Hint: it’s not the vtable.<br />
4 &#8211; Hint: it’s probably not about where you declared a variable.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/fintanp.wordpress.com/34/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/fintanp.wordpress.com/34/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/fintanp.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/fintanp.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/fintanp.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/fintanp.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/fintanp.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/fintanp.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/fintanp.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/fintanp.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/fintanp.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/fintanp.wordpress.com/34/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=fintanp.wordpress.com&blog=112271&post=34&subd=fintanp&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://fintanp.wordpress.com/2007/03/15/premature-optimization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9fefd4a9c0730bf11295b7f5bc1f685d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fintanp</media:title>
		</media:content>
	</item>
	</channel>
</rss>