<?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>scriptNode &#187; benchmarks</title>
	<atom:link href="http://scriptnode.com/tag/benchmarks/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptnode.com</link>
	<description>Tips and tricks for web developers.</description>
	<lastBuildDate>Tue, 01 Sep 2009 18:46:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Google Chrome Benchmarks</title>
		<link>http://scriptnode.com/article/google-chrome-benchmarks/</link>
		<comments>http://scriptnode.com/article/google-chrome-benchmarks/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 07:39:18 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=91</guid>
		<description><![CDATA[
So unless you&#8217;ve been living under a rock, you&#8217;ve probably heard about the release of Google Chrome. Being a hardcore Firefox nut myself, I&#8217;m not just skeptical, I&#8217;m largely indifferent. With Firebug, I&#8217;ve got the perfect web developer environment, so I&#8217;m good to go. It would be hard to sell me on something else.


Google is [...]]]></description>
			<content:encoded><![CDATA[<p>
So unless you&#8217;ve been living under a rock, you&#8217;ve probably heard about <a href="http://googleblog.blogspot.com/2008/09/fresh-take-on-browser.html">the release</a> of <a href="http://www.google.com/chrome">Google Chrome</a>. Being a hardcore <a href="http://www.mozilla.com/">Firefox</a> nut myself, I&#8217;m not just skeptical, I&#8217;m largely indifferent. With <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a>, I&#8217;ve got the perfect web developer environment, so I&#8217;m good to go. It would be hard to sell me on something else.
</p>
<p>
Google is a buzzworthy company, though, and I&#8217;ve already heard from everyone and their mom about how simple, clean and (most notably), <strong>fast</strong> the browser is. This piqued my interest. Time for more benchmarks!
</p>
<p>
I really thought I&#8217;d published more <a href="/tag/benchmarks/">benchmark articles</a> by now, but there were only two, so amending them was quick and easy. Here are the results:
</p>
<h3><a href="/article/try-catch-benchmark/">Try&#8230; Catch Benchmark</a></h3>
<p>
This benchmark was setup to see how quickly the standard browsers could execute code that was throwing (and catching) errors. <a href="/article/try-catch-benchmark/">Read the full article here.</a>
</p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th>Solo</th>
<th>With <code>try...catch</code></th>
<th>With <code>try...catch</code> and an error</th>
</tr>
<tr>
<td>Firefox 2</td>
<td>36 milliseconds</td>
<td>47 milliseconds</td>
<td class="error">32.917 seconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td>3 milliseconds</td>
<td>4 milliseconds</td>
<td>156 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">0 milliseconds</td>
<td>6 milliseconds</td>
<td>69 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>209 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>178 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera </td>
<td>6 milliseconds</td>
<td>10 milliseconds</td>
<td class="error">3.011 seconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>13 milliseconds</td>
<td>16 milliseconds</td>
<td>50 milliseconds</td>
</tr>
</table>
<p>
As you can see, <strong>Chrome</strong> is among the highest performers. It executes the plain code insanely fast (never more than 1 millisecond in any of my tests), and is only second to <strong>Safari 3</strong> in terms of catching errors quickly.
</p>
<h3><a href="/article/conditional-benchmarks/">Conditional Benchmarks</a></h3>
<p>
This benchmark is a little more abstract. The objective was to determine which conditional is fastest among <code>if</code>, <code>switch</code> and what I call an <strong>object conditional</strong>.
</p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th><code>if</code> block</th>
<th><code>switch</code> statement</th>
<th>object conditional</th>
</tr>
<tr>
<td>Firefox 2</td>
<td class="worst">444 milliseconds</td>
<td>425 milliseconds</td>
<td class="best">310 milliseconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td class="worst">50 milliseconds</td>
<td class="best">38 milliseconds</td>
<td>42 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">11 milliseconds</td>
<td class="best">11 milliseconds</td>
<td>20 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td class="worst">353 milliseconds</td>
<td>347 milliseconds</td>
<td class="best">290 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td class="worst">375 milliseconds</td>
<td>381 milliseconds</td>
<td class="best">344 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera 9.5</td>
<td class="best">50 milliseconds</td>
<td class="worst">55 milliseconds</td>
<td>54 milliseconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>150 milliseconds</td>
<td class="worst">156 milliseconds</td>
<td class="best">137 milliseconds</td>
</tr>
</table>
<p>
Turns out, that was no fluke earlier. <strong>Chrome easily blows away the competition</strong> here. I might question Google&#8217;s motives (and I certainly think it&#8217;s a tad shady to have renewed their contract with their now-competitor and then release competing software), but I applaud their speed of my beloved JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/google-chrome-benchmarks/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Conditional Benchmarks</title>
		<link>http://scriptnode.com/article/conditional-benchmarks/</link>
		<comments>http://scriptnode.com/article/conditional-benchmarks/#comments</comments>
		<pubDate>Mon, 01 Sep 2008 07:08:30 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=83</guid>
		<description><![CDATA[

As most JavaScript programmers know (and many are all-too familiar with), speed is a major factor
when considering how to accomplish any given task.
Once in a while, a script will still run too slowly even after standard optimization tricks have been applied.
When this happens, it makes sense to revisit common practices to see if they can [...]]]></description>
			<content:encoded><![CDATA[<p><!-- i can no haz yuiblog :( --></p>
<p>
As most JavaScript programmers know (and many are all-too familiar with), speed is a major factor<br />
when considering how to accomplish any given task.<br />
Once in a while, a script will <em>still</em> run too slowly even after standard optimization tricks have been applied.<br />
When this happens, it makes sense to revisit common practices to see if they can be improved.</p>
<p>
I&#8217;ve noticed that much of the code that I write contains large <code>if</code> blocks and <code>switch</code> statements. Going back and reading what I&#8217;ve written,<br />
I sometimes can&#8217;t figure out why I chose one method over the other, given that they can both get the same job done. Usually I think readability is a factor, but which method is<br />
more readable is typically subjective, making that irrelevant.
</p>
<p>
One use case in which <code>if</code> may be an obvious choice is if the conditionals needed do not translate well into a <code>switch</code>. Here&#8217;s an example:</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
if (((foo === 1) &amp;&amp; (!bar)) || ((foo &gt;= 15) &amp;&amp; (bar !== false))) {<br />
	// It would be messy to make this a switch statement<br />
}<br />
</textarea></p>
<p>
The above block already lacks a bit in readability, and converting it to <code>switch</code> would be a nightmare.<br />
In this instance, <code>if</code> is the clear choice because of its flexibility. In many cases though, a single variable is being checked in a large set of conditionals.<br />
This is the use case that I wanted to explore.
</p>
<p>
To me, JavaScript is all about doing things in clever new ways to overcome limitations.<br />
Given that JavaScript is such an expressive, powerful language, is there a different approach that could be taken regarding these conditional blocks?<br />
One method that can be used is what I call an <em>object conditional</em>.<br />
(This concept is <a href="http://blogs.msdn.com/ie/archive/2006/11/16/ie-javascript-performance-recommendations-part-2-javascript-code-inefficiencies.aspx">not new to the front-end engineering world</a>.)<br />
In the example below I have setup a common, easily readable <code>if</code> block (commented out). After that is the same behavior as described in an object:</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Get the value from the select box<br />
var bro = document.getElementById(&#8217;example-1-select&#8217;).value;</p>
<p>/*<br />
if (bro == &#8216;mario&#8217;) {<br />
	alert(&#8221;You selected Mario Mario!!&#8221;);<br />
} else if (bro == &#8216;luigi&#8217;) {<br />
	alert(&#8221;You selected Luigi Mario!&#8221;);<br />
} else {<br />
	alert(&#8221;That&#8217;s not a Mario brother&#8221;);<br />
}<br />
*/</p>
<p>var testObject = {<br />
	&#8216;mario&#8217; : function() {<br />
		alert(&#8221;You selected Mario Mario!&#8221;);<br />
	},<br />
	&#8216;luigi&#8217; : function() {<br />
		alert(&#8221;You selected Luigi Mario!&#8221;);<br />
	}<br />
};</p>
<p>if (bro in testObject) {<br />
	testObject[bro]();<br />
} else {<br />
	alert(&#8221;That&#8217;s not a Mario brother&#8221;);<br />
}<br />
</textarea></p>
<p>
You can run this example by pressing the button below:
</p>
<p>
	<label for="example-1-select">Select a Mario brother:</label></p>
<select id="example-1-select">
		<option value="mario">Mario</option></p>
<p>		<option value="luigi">Luigi</option><br />
		<option value="princess">Princess Toadstool</option><br />
	</select>
<p>	<button id="example-1-exec">Execute this example</button>
</p>
<p><script type="text/javascript">
<!--//
YAHOO.util.Event.addListener('example-1-exec', 'click', function() {</p>
<p>	var bro = document.getElementById('example-1-select').value;</p>
<p>	var testObject = {
		'mario' : function() {
			alert("You selected Mario Mario!");
		},
		'luigi' : function() {
			alert("You selected Luigi Mario!");
		}
	};</p>
<p>	if (bro in testObject) {
		testObject[bro]();
	} else {
		alert("That's not a Mario brother");
	}</p>
<p>});
//-->
</script></p>
<p>There are many things to consider here.<br />
The first and most obvious being that the object conditional itself uses an <code>if</code> block, making it seem like it would be slower than the <code>if</code> alone right off the bat.<br />
The only other way to emulate both <code>else</code> and <code>default</code> without getting the error <em>testObject[bro] is not a function</em><br />
is with a <code>try...catch</code> statement.<br />
Since we all know that <a href="http://scriptnode.com/article/try-catch-benchmark/">catching errors is really slow</a>, that&#8217;s not an option when we&#8217;re going for<br />
high performance. So we&#8217;ll have to settle for using an <code>if</code>.</p>
<p>
Something else to consider is that the scope is lost when calling a function, a problem that&#8217;s not an issue using the other two methods.<br />
This is easily solved, however, by passing whatever you&#8217;d like into the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Function:call">function call</a>, for example:
</p>
<p>
<code>testObject[val].call(args, this, etc);</code>
</p>
<p>
Now that we&#8217;ve got our three different methods, let&#8217;s find out which is fastest!
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var benchmark = function(runs, id, func) {</p>
<p>	var<br />
		mStart = new Date().getTime(),<br />
		vals = ['a','b','c','d','e'],<br />
		len = vals.length;</p>
<p>	for (var r = 0; r &lt; runs; r++) {<br />
		for (var i = 0; i &lt; len; i++) {<br />
			func(vals[i]);<br />
		}<br />
	}</p>
<p>	var mStop = new Date().getTime(),<br />
		elapsed = (mStop &#8211; mStart);</p>
<p>	document.getElementById(id).innerHTML = elapsed + &#8216; millisecond&#8217; + ((elapsed == 1) ? &#8221; : &#8217;s&#8217;);</p>
<p>};</p>
<p>function funcA() {};<br />
function funcB() {};<br />
function funcC() {};<br />
function funcD() {};<br />
function funcE() {};</p>
<p>var testIf = function(val) {<br />
	if (val == &#8216;a&#8217;) {<br />
		funcA();<br />
	} else if (val == &#8216;b&#8217;) {<br />
		funcB();<br />
	} else if (val == &#8216;c&#8217;) {<br />
		funcC();<br />
	} else if (val == &#8216;d&#8217;) {<br />
		funcD();<br />
	} else {<br />
		funcE();<br />
	}<br />
};</p>
<p>var testSwitch = function(val) {<br />
	switch (val) {<br />
		case &#8216;a&#8217; :<br />
			funcA();<br />
			break;<br />
		case &#8216;b&#8217;:<br />
			funcB();<br />
			break;<br />
		case &#8216;c&#8217;:<br />
			funcC();<br />
			break;<br />
		case &#8216;d&#8217;:<br />
			funcD();<br />
			break;<br />
		default :<br />
			funcE();<br />
			break;<br />
	}<br />
};</p>
<p>var testObject = {<br />
	&#8216;a&#8217; : funcA,<br />
	&#8216;b&#8217; : funcB,<br />
	&#8216;c&#8217; : funcC,<br />
	&#8216;d&#8217; : funcD<br />
};</p>
<p>var testObjectCond = function(val) {<br />
	if (val in testObject) {<br />
		testObject[val]();<br />
	} else {<br />
		funcE();<br />
	}<br />
};</p>
<p>benchmark(10000, &#8216;benchmark-if-res&#8217;, testIf);<br />
benchmark(10000, &#8216;benchmark-switch-res&#8217;, testSwitch);<br />
benchmark(10000, &#8216;benchmark-object-res&#8217;, testObjectCond);<br />
</textarea></p>
<p>
This benchmark sets up three different tests, one with <code>if</code>, one with <code>switch</code>, and one using an object conditional.<br />
Each method checks four different values and then falls into the default, for a total of five states.<br />
This is executed 10,000 times to get a good sampling to work with.<br />
You can execute this benchmark yourself below:
</p>
<div class="section">
<p>	<fieldset><br />
		<legend>Results:</legend></p>
<ul>
<li><code>if</code> block: <span id="benchmark-if-res">(execute to view)</span></li>
<li><code>switch</code> statement: <span id="benchmark-switch-res">(execute to view)</span></li>
<li>object conditional: <span id="benchmark-object-res">(execute to view)</span></li>
</ul>
<p>	</fieldset></p>
<p>	<button id="benchmark-exec">Execute benchmark</button></p>
</div>
<p><script type="text/javascript">
<!--//
YAHOO.util.Event.addListener('benchmark-exec', 'click', function() {</p>
<p>	var benchmark = function(runs, id, func) {</p>
<p>		var
			mStart = new Date().getTime(),
			vals = ['a','b','c','d','e'],
			len = vals.length;</p>
<p>		for (var r = 0; r < runs; r++) {
			for (var i = 0; i < len; i++) {
				func(vals[i]);
			}
		}</p>
<p>		var mStop = new Date().getTime(),
			elapsed = (mStop - mStart);</p>
<p>		document.getElementById(id).innerHTML = elapsed + ' millisecond' + ((elapsed == 1) ? '' : 's');</p>
<p>	};</p>
<p>	function funcA() {};
	function funcB() {};
	function funcC() {};
	function funcD() {};
	function funcE() {};</p>
<p>	var testIf = function(val) {
		if (val == 'a') {
			funcA();
		} else if (val == 'b') {
			funcB();
		} else if (val == 'c') {
			funcC();
		} else if (val == 'd') {
			funcD();
		} else {
			funcE();
		}
	};</p>
<p>	var testSwitch = function(val) {
		switch (val) {
			case 'a' :
				funcA();
				break;
			case 'b':
				funcB();
				break;
			case 'c':
				funcC();
				break;
			case 'd':
				funcD();
				break;
			default :
				funcE();
				break;
		}
	};</p>
<p>	var testObject = {
		'a' : funcA,
		'b' : funcB,
		'c' : funcC,
		'd' : funcD
	};</p>
<p>	var testObjectCond = function(val) {
		if (val in testObject) {
			testObject[val]();
		} else {
			funcE();
		}
	};</p>
<p>	benchmark(10000, 'benchmark-if-res', testIf);
	benchmark(10000, 'benchmark-switch-res', testSwitch);
	benchmark(10000, 'benchmark-object-res', testObjectCond);</p>
<p>});
//-->
</script></p>
<p>
Results will vary of course, but I compiled my findings in the table below.<br />
Using Windows XP, I ran the tests ten times in each of the common browsers and recorded the averages:
</p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th><code>if</code> block</th>
<th><code>switch</code> statement</th>
<th>object conditional</th>
</tr>
<tr>
<td>Firefox 2</td>
<td class="worst">444 milliseconds</td>
<td>425 milliseconds</td>
<td class="best">310 milliseconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td class="worst">50 milliseconds</td>
<td class="best">38 milliseconds</td>
<td>42 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">11 milliseconds</td>
<td class="best">11 milliseconds</td>
<td>20 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td class="worst">353 milliseconds</td>
<td>347 milliseconds</td>
<td class="best">290 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td class="worst">375 milliseconds</td>
<td>381 milliseconds</td>
<td class="best">344 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera 9.5</td>
<td class="best">50 milliseconds</td>
<td class="worst">55 milliseconds</td>
<td>54 milliseconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>150 milliseconds</td>
<td class="worst">156 milliseconds</td>
<td class="best">137 milliseconds</td>
</tr>
</table>
<p>
It looks like the winner in terms of speed is usually the clever contendor, the object conditional.<br />
But not by a large margin. There&#8217;s a lot to be said about code readability, so if<br />
using this method will make your application harder to maintain, it may not be worth it.<br />
Indeed, my colleague <a href="http://crockford.com/">Douglas Crockford</a> (Yahoo!&#8217;s JavaScript architect) has good cautionary advice here:
</p>
<blockquote><p>
In chosing how to structure a program, the first priority has to be clarity of expression. From clarity comes correctness and maintainability. Subordinating clarity to save milliseconds should be discouraged. That is the wrong motivation.
</p>
</blockquote>
<p>
This is certainly true, but sometimes structure unfortunately needs to take a back seat to performance.<br />
The most common use case that comes to my mind is animation.
</p>
<p>
Say for example, you are implementing an animation that moves an element across the screen and must perform complex calculations over each iteration.<br />
Using an animation library like <a href="http://developer.yahoo.com/yui/animation/">the one YUI provides</a>, the code might look something like this:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var anim = new YAHOO.util.Anim(<br />
	&#8216;example&#8217;,<br />
	{left : {to : 1000}},<br />
	0.1<br />
);</p>
<p>anim.onTween.subscribe(function() {<br />
	// This function must be as optimal as possible<br />
});</p>
<p>anim.animate();<br />
</textarea></p>
<p>
Given this example, optimization is critical, and those few milliseconds gained by using a quicker pattern<br />
could make the difference between a great user experience and a sluggish one.
</p>
<p>
What are your thoughts? I look forward to your feedback in the comments section.
</p>
<p>
<strong>Edit 9/02/08:</strong> Added <a href="http://www.google.com/chrome">Google Chrome</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/conditional-benchmarks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Try&#8230; Catch Benchmark</title>
		<link>http://scriptnode.com/article/try-catch-benchmark/</link>
		<comments>http://scriptnode.com/article/try-catch-benchmark/#comments</comments>
		<pubDate>Mon, 16 Jun 2008 00:34:50 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=25</guid>
		<description><![CDATA[
The try...catch statement in JavaScript is a common tool, especially useful in a programming environment as volatile as the web.
Since I always try to make my scripts execute as quickly as possible, I was curious about the performance hit when using try...catch extensively.
Below is a benchmark testing three methods:


A simple, bare-bones variable definition
The same code, [...]]]></description>
			<content:encoded><![CDATA[<p>
The <code>try...catch</code> statement in JavaScript is a common tool, especially useful in a programming environment as volatile as the web.<br />
Since I always try to make my scripts execute as quickly as possible, I was curious about the performance hit when using <code>try...catch</code> extensively.<br />
Below is a benchmark testing three methods:
</p>
<ol>
<li>A simple, bare-bones variable definition</li>
<li>The same code, but with a <code>try...catch</code> block</li>
<li>The same code, but with a <code>try...catch</code> block <strong>and</strong> an intentional error</li>
</ol>
<p>
Here&#8217;s the source code:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var benchmark = function(runs, id, func) {</p>
<p>	var mStart = new Date().getTime();</p>
<p>	for (var i = 0; i &lt; runs; i++) {<br />
		func();<br />
	}</p>
<p>	var mStop = new Date().getTime(),<br />
		elapsed = (mStop &#8211; mStart);</p>
<p>	document.getElementById(id).innerHTML = elapsed + &#8216; millisecond&#8217; + ((elapsed == 1) ? &#8221; : &#8217;s&#8217;);</p>
<p>};</p>
<p>var solo = function() {<br />
	var giveHim = &#8216;all the guns&#8217;;<br />
};</p>
<p>var withTryCatch = function() {<br />
	try {<br />
		var giveHim = &#8216;all the guns&#8217;;<br />
	} catch(e) {}<br />
};</p>
<p>var withTryCatchAndError = function() {<br />
	var does = {};<br />
	try {<br />
		does.not.exist = &#8216;all the guns&#8217;;<br />
	} catch(e) {}<br />
};</p>
<p>benchmark(10000, &#8216;benchmark-solo&#8217;, solo);<br />
benchmark(10000, &#8216;benchmark-try-catch&#8217;, withTryCatch);<br />
benchmark(10000, &#8216;benchmark-try-catch-error&#8217;, withTryCatchAndError);<br />
</textarea></p>
<p>
As you can see, each test is executed 10,000 times to get a good sampling of how long each is taking.<br />
Please note that this script <strong>could lock up your browser</strong> for a few moments (or even crash it), but you can run this benchmark yourself below:
</p>
<div class="section">
<p>	<fieldset><br />
		<legend>Results:</legend></p>
<ul>
<li>Solo: <span id="benchmark-solo">execute to view</span></li>
<li>With <code>try...catch</code> statement: <span id="benchmark-try-catch">execute to view</span></li>
<li>With <code>try...catch</code> statement <strong>and</strong> an error: <span id="benchmark-try-catch-error">execute to view</span></li>
</ul>
<p>	</fieldset></p>
<p>	<button id="benchmark-exec">Execute benchmark</button></p>
</div>
<p><script type="text/javascript">
<!--//
YAHOO.util.Event.addListener('benchmark-exec', 'click', function() {</p>
<p>	var benchmark = function(runs, id, func) {</p>
<p>		var mStart = new Date().getTime();</p>
<p>		for (var i = 0; i < runs; i++) {
			func();
		}</p>
<p>		var mStop = new Date().getTime(),
			elapsed = (mStop - mStart);</p>
<p>		document.getElementById(id).innerHTML = elapsed + ' millisecond' + ((elapsed == 1) ? '' : 's');</p>
<p>	};</p>
<p>	var solo = function() {
		var giveHim = 'all the guns';
	};</p>
<p>	var withTryCatch = function() {
		try {
			var giveHim = 'all the guns';
		} catch(e) {}
	};</p>
<p>	var withTryCatchAndError = function() {
		var does = {};
		try {
			does.not.exist = 'all the guns';
		} catch(e) {}
	};</p>
<p>	benchmark(10000, 'benchmark-solo', solo);
	benchmark(10000, 'benchmark-try-catch', withTryCatch);
	benchmark(10000, 'benchmark-try-catch-error', withTryCatchAndError);</p>
<p>});
//-->
</script></p>
<p>
Using Windows XP, I executed this script ten times using each of the common browsers, taking the averages and compiling them in the <a href="#results">table below</a>:
</p>
<p><a name="results"></a></p>
<table cellpadding="3" cellspacing="0" class="results">
<tr>
<th>Browser</th>
<th>Solo</th>
<th>With <code>try...catch</code></th>
<th>With <code>try...catch</code> and an error</th>
</tr>
<tr>
<td>Firefox 2</td>
<td>36 milliseconds</td>
<td>47 milliseconds</td>
<td class="error">32.917 seconds</td>
</tr>
<tr class="toggle">
<td>Firefox 3</td>
<td>3 milliseconds</td>
<td>4 milliseconds</td>
<td>156 milliseconds</td>
</tr>
<tr>
<td>Google Chrome</td>
<td class="best">0 milliseconds</td>
<td>6 milliseconds</td>
<td>69 milliseconds</td>
</tr>
<tr class="toggle">
<td>Internet Explorer 6</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>209 milliseconds</td>
</tr>
<tr>
<td>Internet Explorer 7</td>
<td>33 milliseconds</td>
<td>35 milliseconds</td>
<td>178 milliseconds</td>
</tr>
<tr class="toggle">
<td>Opera </td>
<td>6 milliseconds</td>
<td>10 milliseconds</td>
<td class="error">3.011 seconds</td>
</tr>
<tr>
<td>Safari 3</td>
<td>13 milliseconds</td>
<td>16 milliseconds</td>
<td>50 milliseconds</td>
</tr>
</table>
<p>
Based on this benchmark, it appears that <code>try...catch</code> adds negligible overhead on its own;<br />
it&#8217;s the handling of errors that can add signifant execution time to your scripts.<br />
Internet Explorer and Safari seem to handle errors very quickly, while Opera and especially Firefox could potentially completely ruin a user experience<br />
(such as <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html#event_onTween">animation tweening</a>) using this method. Be warned!
</p>
<p>
<strong>Edit 7/11/08:</strong> Added <a href="http://www.spreadfirefox.com/en-US/worldrecord/firefox3">Firefox 3</a>.
</p>
<p>
<strong>Edit 9/02/08:</strong> Added <a href="http://www.google.com/chrome">Google Chrome</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/try-catch-benchmark/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
