<?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>Eric Hynds &#187; JavaScript</title>
	<atom:link href="http://www.erichynds.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.erichynds.com</link>
	<description>Web Developer&#039;s Ramblings on JavaScript, jQuery, ColdFusion, MySQL, and other technologies.</description>
	<lastBuildDate>Tue, 07 Sep 2010 14:26:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Working With XML, jQuery, and JavaScript</title>
		<link>http://www.erichynds.com/jquery/working-with-xml-jquery-and-javascript/</link>
		<comments>http://www.erichynds.com/jquery/working-with-xml-jquery-and-javascript/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 16:44:34 +0000</pubDate>
		<dc:creator>Eric Hynds</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[dom]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.erichynds.com/?p=886</guid>
		<description><![CDATA[A recent requirement of mine was to convert large CSV files to XML, and then build an accompanying interface to update &#38; manage the data.  jQuery was most useful for traversing &#38; manipulating the large DOM&#8217;s, but I did run across a few gotcha&#8217;s worthy of discussion.  There doesn&#8217;t seem to be much info on [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.erichynds.com%2Fjquery%2Fworking-with-xml-jquery-and-javascript%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.erichynds.com%2Fjquery%2Fworking-with-xml-jquery-and-javascript%2F&amp;source=erichynds&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>A recent requirement of mine was to convert large CSV files to XML, and then build an accompanying interface to update &amp; manage the data.  jQuery was most useful for traversing &amp; manipulating the large DOM&#8217;s, but I did run across a few gotcha&#8217;s worthy of discussion.  There doesn&#8217;t seem to be much info on the interwebs about XML and jQuery outside of an XHR request, so here&#8217;s what I picked up along the way.</p>
<h2>You cannot pass an XML string to jQuery&#8217;s constructor</h2>
<p>Well <em>technically </em>you can, but it&#8217;s <a href="http://api.jquery.com/jQuery/#html" target="_blank">not</a> <a href="http://dev.jquery.com/ticket/6796#comment:2" target="_blank">supported</a> and jQuery will not treat the string as XML.  You&#8217;ll still be working with an HTML document object.  jQuery has no idea/doesn&#8217;t care that the elements are not valid HTML elements though, so this might be just fine as long as your XML remains detached from the DOM.  To feed XML to jQuery correctly, you must pass a parsed XML string (a la XML object) to jQuery&#8217;s constructor.</p>
<p>A <a href="http://dev.jquery.com/ticket/6693" target="_blank">new feature ticket</a> exists to add cross-browser XML compatibility to jQuery, whose summary yields another good nugget of info:</p>
<blockquote><p><em>As documented, the $(&#8220;&lt;html string&gt;&#8221;) method only supports parsing HTML strings, but users often try to parse XML strings with it. This doesn&#8217;t work since jQuery uses the .innerHTML property for parsing and implicitly enforces HTML rules on the string. IE in particular will throw errors or misparse XML strings passed to $() in this way.</em></p></blockquote>
<p>Furthermore, the second you try to pass any sizable XML or HTML string to jQuery&#8217;s constructor, Firefox 3 is going to fail with a &#8220;<em>script stack space quota is exhausted</em>&#8221; error (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=579656" target="_blank">see the bug report</a> filed with Mozilla).</p>
<p style="text-align: center;"><img src="/examples/xml/firefoxerror.png" alt="script stack space quota is exhausted" /></p>
<p>As Dave Methuin (core team member) <a href="http://dev.jquery.com/ticket/6796" target="_blank">explains</a>:</p>
<blockquote><p><em>Firefox seems to be dying on the constructor check for HTML, which uses a RegExp?:</em></p>
<p><em>match = quickExpr.exec( selector );</em></p>
<p><em>The string you&#8217;re passing in is long and html-ish, and I suspect Firefox  is backtracking heavily trying to match the huge string. We can either  assume a long (&gt;1K chars) string must be HTML or come up with a RegExp? that doesn&#8217;t need to backtrack so much.</em></p></blockquote>
<p>So how do you convert a string to an XML object?  It depends on your browser.<span id="more-886"></span></p>
<h2>Parse an XML string into a DOM</h2>
<p><em>The following only applies if you&#8217;re manually parsing an string.  If using XMLHttpRequest the browser does all this automatically &#8211; just use the responseXML property.</em></p>
<p>To re-iterate, jQuery alone is not capable of parsing XML strings.  You will need to leverage the DOM parsing method baked into the browser, which all support in one form another.  Firefox, Chrome, and Safari have a <a href="https://developer.mozilla.org/En/DOMParser" target="_blank">DOMParser object</a>, and IE uses their proprietary ActiveX object.  To create a cross-browser solution:</p>
<p><script src="http://gist.github.com/553364.js?file=gistfile1.js"></script> This snippet checks for the absence of <code>DOMParser</code> in the window scope, and if true, defines it.  If the browser has an <code>ActiveXObject</code> (IE),  the <code>MLXML.DomDocument</code> method is used to convert the string to an DOM.  If <code>ActiveXObject</code> isn&#8217;t present but <code>XMLHttpRequest</code> is (fail-safe), a pseudo AJAX request is created and the parsed string is returned in the <code>responseXML</code> property of <code>XMLHttpRequest</code>.
<p>Now that we have a normalized <code>DOMParser</code>, parsing XML is easy:</p>
<p>    <script src="http://gist.github.com/554152.js?file=gistfile1.js"></script></p>
<h2>Converting an XML DOM back to a string</h2>
<p>Again, IE has a different implementation than everyone else, but it&#8217;s still trivial to normalize.  Firefox/Chrome/Safari use the <code>XMLSerializer.serializeToString</code> method, whereas IE has an &#8220;xml&#8221; property on the XML object.</p>
<p><script src="http://gist.github.com/554178.js?file=XMLSerializer.js"></script></p>
<h2>$.data() is unreliable</h2>
<p><img style="float: right; padding: 0 0 5px 5px;" src="/examples/xml/expando.png" alt="jQuery.expando" /></p>
<p>First a note on how <code>$.data</code> actually works.  When jQuery is loaded, <code>$.expando</code> is set to the current timestamp prefixed with &#8220;jQuery&#8221;.  Expando becomes the name of a property set on elements when data is added via <code>$.data</code>/<code>$.fn.data</code>.  The expando&#8217;s value is a UUID and acts as jQuery&#8217;s link back to the proper store in <code>$.cache</code> &#8211; where the data is actually stored.  Each key in the <code>$.cache</code> object is the UUID.</p>
<p>That said, the ActiveX object that IE uses for XML parsing has issue with jQuery trying to set expando properties on elements.  And instead of working around this issue, <a href="http://dev.jquery.com/ticket/6890" target="_blank">it appears</a> that the solution will be to document the fact that <code>$.data</code> doesn&#8217;t work cross-browser on XML documents.</p>
<p>Therefore, avoid setting data on XML documents.</p>
<h2>getElementById will always return null</h2>
<p>If part of your performance plan involves setting id attributes to leverage the speed of <code>getElementById</code>, think again. <code>getElementById</code> does not work on XML documents.</p>
<p>As documented in Mozilla&#8217;s <a href="https://developer.mozilla.org/en/document.getElementById" target="_blank">MDC</a>:</p>
<blockquote><p><em>DOM implementation must have information that says which attributes are of type ID. Attributes with the name &#8220;id&#8221; are not of type ID unless so defined in the document&#8217;s DTD. The id attribute is defined to be of ID type in the common cases of XHTML, XUL, and other. Implementations that do not know whether attributes are of type ID or not are expected to return null.</em></p></blockquote>
<p>&#8220;ID&#8221; is a data type, and in an XML document, the browser has no clue that an attribute named &#8220;id&#8221; should be interpreted as such. The same applies for the class attribute and <code>getElementsByClassName</code>, but have no fear; <code>getElementsByTagName</code> (and <code>querySelector</code>/<code>querySelectorAll</code> in modern browsers) will continue to work as expected.</p>
<p>jQuery&#8217;s Sizzle (and probably all other selector engines) account for this, so <code>$("#id")</code> will continue to work as expected.  Just don&#8217;t expect the same performance as <code>getElementById</code>.</p>
<p>The only benefit I see to passing raw XML to jQuery(), without parsing it into an XML DOM first, is the fact that <code>getElementById</code> will continue to work.  I still wouldn&#8217;t recommend it though.</p>
<h2>$.isXMLDoc()</h2>
<p>This little <a href="http://api.jquery.com/jQuery.isXMLDoc/" target="_blank">utility method</a> exists for testing whether or not a DOM node is within an XML document:</p>
<p><script src="http://gist.github.com/559144.js?file=isxmldoc.js"></script></p>
<p>Useful when you want to be certain you&#8217;re correctly passing an XML DOM to jQuery.</p>
<h2>No XML love in WebWorkers</h2>
<p>Initially, part of my performance strategy in this project was to leverage WebWorkers to avoid locking up the main UI thread.  After consulting the brilliance at <a href="http://bocoup.com" target="_blank">Bocoup</a>, <a href="http://twitter.com/rwaldron" target="_blank">Rick Waldron</a> noted that XHR objects used within workers will only return <code>responseText</code>, and never <code>responseXML</code>. This is by design as <code>responseXML</code> is not considered thread safe.  The <code>DOMparser</code> object is not available inside workers either, so unless you want to roll your own XML parser (hint: you don&#8217;t) do not try to request or parse XML.</p>
<h2>References</h2>
<p>Most of these links are scattered throughout this post, but if you want them all in one place:</p>
<ul>
<li style="margin-bottom: 10px;">jQuery ticket for &#8220;Error &#8216;script stack space quota is exhausted&#8217;&#8221; error<br />
<a href="http://dev.jquery.com/ticket/6796">http://dev.jquery.com/ticket/6796</a></li>
<li style="margin-bottom: 10px;">Mozilla ticket for &#8220;Error &#8216;script stack space quota is exhausted&#8217;&#8221;<br />
<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=579656">https://bugzilla.mozilla.org/show_bug.cgi?id=579656</a></li>
<li style="margin-bottom: 10px;">jQuery ticket for $.data fails on XML documents in IE<br />
<a href="http://dev.jquery.com/ticket/6890">http://dev.jquery.com/ticket/6890</a></li>
<li style="margin-bottom: 10px;">MDC DOMParser Object<br />
<a href="https://developer.mozilla.org/en/DOMParser">https://developer.mozilla.org/en/DOMParser</a></li>
<li style="margin-bottom: 10px;">MDC XMLSerializer Object<br />
<a href="https://developer.mozilla.org/en/XMLSerializer">https://developer.mozilla.org/en/XMLSerializer</a></li>
<li style="margin-bottom: 10px;">MDC getElementById<br />
<a href="https://developer.mozilla.org/en/document.getElementById">https://developer.mozilla.org/en/document.getElementById</a></li>
<li style="margin-bottom: 10px;">jQuery&#8217;s constructor API documentation<br />
<a href="http://api.jquery.com/jQuery/#html">http://api.jquery.com/jQuery/</a></li>
<li style="margin-bottom:10px">$.isXMLDoc() API documentation<br /><a href="http://api.jquery.com/jQuery.isXMLDoc/">http://api.jquery.com/jQuery.isXMLDoc/</a></li>
<li style="margin-bottom:10px">Add cross-browser XML support to jQuery &#8211; feature enhancement ticket<br /><a href="http://dev.jquery.com/ticket/6693">http://dev.jquery.com/ticket/6693</a>
</li>
</ul>
<p>If you know of any other XML gotcha&#8217;s, please leave them in the comments below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.erichynds.com/jquery/working-with-xml-jquery-and-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery and Performance: What is &#8216;this&#8217;?</title>
		<link>http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/</link>
		<comments>http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 14:14:50 +0000</pubDate>
		<dc:creator>Eric Hynds</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.erichynds.com/?p=173</guid>
		<description><![CDATA[In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol&#8217; JavaScript, and a good place to start is with &#8216;this&#8216;. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference [...]


Related posts:<ol><li><a href='http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/' rel='bookmark' title='Permanent Link: JavaScript Loop Performance: Caching the &#8216;.length&#8217; Property of an Array'>JavaScript Loop Performance: Caching the &#8216;.length&#8217; Property of an Array</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.erichynds.com%2Fjquery%2Fjquery-and-performance-what-is-this%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.erichynds.com%2Fjquery%2Fjquery-and-performance-what-is-this%2F&amp;source=erichynds&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery.  That is, find a balance between using jQuery and plain ol&#8217; JavaScript, and a good place to start is with &#8216;<code>this</code>&#8216;. Many developers use $(this) exclusively as their hammer inside callbacks and forget about <code>this</code>, but the difference is distinct:</p>
<p>When inside a jQuery method&#8217;s anonymous callback function, <code>this</code> is a reference to the current DOM element.  $(this) turns <code>this</code> into a jQuery object and exposes jQuery&#8217;s methods.  A jQuery object is nothing more than a beefed-up array of DOM elements.</p>
<h2>Digging a little deeper</h2>
<p>As you begin to nest functions the context of <code>this</code> changes:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;#&quot;</span><span style="color: #339933;">&gt;&lt;</span>span<span style="color: #339933;">&gt;</span>Hello World<span style="color: #339933;">&lt;/</span>span<span style="color: #339933;">&gt;&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	event.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In this example I save <code>this</code> to the variable &#8220;self&#8221; so it can be referenced inside the each() loop.  Otherwise it&#8217;s impossible to reference <code>this</code> as the anchor element inside the loop, because <code>this</code> is now the &#8220;span&#8221; DOM element.</p>
<p>Depending on what you&#8217;re doing, using <code>this</code> is sometimes easier and always faster than $(this).  I&#8217;m not talking about scraping jQuery altogether, but rather recognizing that a lot of DOM interaction (especially the simple stuff) can just as easily be done in vanilla JS using <code>this</code>; you are not <em>required</em> to use the jQuery API.  Example:</p>
<p><span id="more-173"></span></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;test.htm&quot;</span><span style="color: #339933;">&gt;</span>Test<span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> href <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">href</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// the href property can be accessed through 'this'</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A more verbose example demonstrating the uses of <code>this</code> and $(this) to get an anchor&#8217;s href value.  These statements are equivalent:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> href<span style="color: #339933;">;</span>
	href <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">href</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// sets &quot;href&quot; to &quot;test.htm&quot;</span>
	href <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;href&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// also sets &quot;href&quot; to &quot;test.htm&quot; after going through the jQuery attr() method.</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// because $(this) is really just a beefed-up array, we can pull off the DOM element using array notation.</span>
	href <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">href</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The point here is that turning <code>this</code> into a jQuery object and using the attr() method is more time consuming than just referencing the &#8220;href&#8221; property of <code>this</code>.  When manipulation is involved the performance implications are even greater.</p>
<h2>Benchmarks</h2>
<p>To quantify my claims, I wrote a profiling function that calculates the execution time of looping a block of code 50,000 times:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> profile <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>label<span style="color: #339933;">,</span> code<span style="color: #339933;">,</span> iterations<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> start<span style="color: #339933;">,</span> total<span style="color: #339933;">,</span> i <span style="color: #339933;">=</span> iterations <span style="color: #339933;">=</span> iterations <span style="color: #339933;">||</span> <span style="color: #CC0000;">50000</span><span style="color: #339933;">;</span>
&nbsp;
	start <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> code.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
	total <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span>start<span style="color: #339933;">;</span>
&nbsp;
	console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>label <span style="color: #339933;">+</span> <span style="color: #3366CC;">': %d ms (looping %l times)'</span><span style="color: #339933;">,</span> total<span style="color: #339933;">,</span> iterations<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I then setup a page with one anchor element and a click event to call the profile function:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// save $(this) and 'this' - their reference change inside the profile function!</span>
	<span style="color: #003366; font-weight: bold;">var</span> $this <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
	console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Accessing the href attribute of a link:'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'$this.attr(&quot;href&quot;)'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		href <span style="color: #339933;">=</span> $this.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;href&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'self.href'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		href <span style="color: #339933;">=</span> self.<span style="color: #660066;">href</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'self.getAttribute(&quot;href&quot;)'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		href <span style="color: #339933;">=</span> self.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;href&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	event.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p class="update"><strong>Update 1/7/2010:</strong> JAlpino pointed out in the comments that the getAttribute(&#8220;href&#8221;) method can be called on <code>this</code> to gain an additional +/- 350ms, as opposed to using <code>this.property</code> syntax.  I&#8217;ve added this method to the benchmarks &amp; results. Thanks, <a href="http://jalpino.com/">JAlpino!</a></p>
<p>The results using jQuery 1.3.2 and 1.4a2 respectively on Firefox 3.5.6:</p>
<div style="text-align: center;"><img src="/examples/this/1-1.gif" alt="" /></div>
<div style="text-align: center;"><img src="/examples/this/1-2.gif" alt="" /></div>
<p><code>self.href</code> provides a 270% improvement when using jQuery 1.3.2 and a 200% improvement when using 1.4a2.  Using the getAttribute() method provides an additional 72% boost over <code>self.href</code>! Keep in mind that in &#8216;the jQuery way&#8217; these numbers do not include the time it takes to convert <code>this</code> into a jQuery object; we&#8217;re caching that outside the profile function, and thus are only benchmarking the performance of the attr() method.  How does <code>this</code> perform over $(this) when used for manipulation?  I ran the profiler again, this time changing the link color to red:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'the jQuery way'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	$this.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;color&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;#ff0000&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'vanilla javascript'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	self.<span style="color: #660066;">style</span>.<span style="color: #660066;">color</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;#ff0000&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<div style="text-align: center;"><img src="/examples/this/2-1.gif" alt="" /></div>
<div style="text-align: center;"><img src="/examples/this/2-2.gif" alt="" /></div>
<p>We&#8217;re looking at a 632% improvement under jQuery 1.3.2 and a 206% improvement under 1.4a2.  Pretty good for changing one line of code.</p>
<h2>Putting <code>this</code> into <code>context</code></h2>
<p>You can pass an optional second argument called context to the jQuery object constructor, which gives jQuery a starting point when searching the DOM for your selector.  The context can be either a DOM element or jQuery object, but ideally should be a DOM element &#8211; like <code>this</code>!  Given the markup below and what we know about <code>this</code> and $(this), the &#8220;span&#8221; child of the anchor can be found four ways:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;testing.htm&quot;</span><span style="color: #339933;">&gt;&lt;</span>span<span style="color: #339933;">&gt;</span>test link<span style="color: #339933;">&lt;/</span>span<span style="color: #339933;">&gt;&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #006600; font-style: italic;">// these statements accomplish the same thing</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first example turns <code>this</code> into a jQuery object and calls the find() method.  The second example looks for a span element using <code>this</code> &#8211; a reference to the anchor DOM element &#8211; as the starting point.  Because the context argument in the third example is a jQuery object, jQuery internally converts the statement to $(this).find(&#8220;span&#8221;), which is equivalent to the first example.  We&#8217;re about to see that this is the slowest method, however, probably due to the overhead in converting the context to a find().  The fourth method is equivalent to $(&#8220;span&#8221;, this), except that <code>this</code> is first converted into a jQuery object, and then the DOM node is pulled off the array.</p>
<p>My original plan going into this blog post was to show you the performance benefits you can gain when using <code>this</code> as the context argument to the jQuery constructor as opposed to $(this), but my results show otherwise.  Note that I ran these tests 20,000 times instead of 50,000 (Firefox got cranky):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// cache $(this) and 'this'</span>
	<span style="color: #003366; font-weight: bold;">var</span> $this <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">' $this.find() '</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		$this.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 20000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">' $(&quot;span&quot;, this) '</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> self<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 20000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">' $(&quot;span&quot;, $this) '</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> $this<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 20000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	profile<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">' $(&quot;span&quot;, $this[0]) '</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;span&quot;</span><span style="color: #339933;">,</span> $this<span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 20000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	event.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<div style="text-align: center;"><img src="/examples/this/3-1.gif" alt="" /></div>
<div style="text-align: center;"><img src="/examples/this/3-2.gif" alt="" /></div>
<p>When using jQuery 1.3.2, $(this).find() was 4% faster than providing a DOM element as the context and 53% faster than using a jQuery object &#8211; pretty negligible.  1.4a2 shipped with some nice speed improvements; the performance of all four are about the same, but $(this).find() is still a bit faster.</p>
<p>To reiterate, I&#8217;m not saying skip jQuery and code everything in plain JS because it&#8217;ll make your site faster.  The speed improvements I pointed out are trivial but can absolutely add up, especially in larger applications.  There are a number of good reasons to use $(this) over <code>this</code>; cross-browser compatibility is one, the extreme ease of use another, but just be aware <code>this</code> exists.</p>
<p>Click <a href="/examples/this/benchmarks.htm">here</a> to see the code and run these benchmarks yourself.</p>


<p>Related posts:<ol><li><a href='http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/' rel='bookmark' title='Permanent Link: JavaScript Loop Performance: Caching the &#8216;.length&#8217; Property of an Array'>JavaScript Loop Performance: Caching the &#8216;.length&#8217; Property of an Array</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>JavaScript Loop Performance: Caching the &#8216;.length&#8217; Property of an Array</title>
		<link>http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/</link>
		<comments>http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 21:52:48 +0000</pubDate>
		<dc:creator>Eric Hynds</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.erichynds.com/?p=146</guid>
		<description><![CDATA[I was reading this article from SitePoint earlier about how inefficient the JavaScript is behind Google&#8217;s new Closure library, and saw some interesting discussion about caching an array&#8217;s length property before entering a &#8216;for&#8217; loop. This is what I&#8217;m talking about: // uncached length property for&#40;var x=0; x &#60; myArray.length; x++&#41;&#123;&#125; &#160; // cached length [...]


Related posts:<ol><li><a href='http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/' rel='bookmark' title='Permanent Link: jQuery and Performance: What is &#8216;this&#8217;?'>jQuery and Performance: What is &#8216;this&#8217;?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.erichynds.com%2Fjavascript%2Fjavascript-loop-performance-caching-the-length-property-of-an-array%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.erichynds.com%2Fjavascript%2Fjavascript-loop-performance-caching-the-length-property-of-an-array%2F&amp;source=erichynds&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I was reading <a href="http://www.sitepoint.com/blogs/2009/11/12/google-closure-how-not-to-write-javascript/" class="blank">this</a> article from SitePoint earlier about how inefficient the JavaScript is behind Google&#8217;s new Closure library, and saw some interesting discussion about caching an array&#8217;s length property before entering a &#8216;for&#8217; loop. This is what I&#8217;m talking about:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// uncached length property</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> myArray.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// cached length property</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x<span style="color: #339933;">=</span>0<span style="color: #339933;">,</span> len<span style="color: #339933;">=</span>myArray.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>I saw this tip and didn&#8217;t think twice about it; I&#8217;ve always been told that caching the length property is indeed faster.  I then saw a couple comments saying otherwise:</p>
<p><span id="more-146"></span></p>
<blockquote>
<p><em>Anyway, the loop performance is not as big deal as you present. Of course, it&#8217;s nicer and more professional to preassign the array length instead of testing it again in every step. But the performance is not such problem. The Javascript basic operations are very fast, making the difference quite unnoticeable. Those two loops performance will differ only in milliseconds for a million-iterations loop in today&#8217;s average computer. This means the same loop traversing an array containing a million items will take about 15 ms if the array.length is tested every time, and about 10 ms if the length is preassigned. So, we are talking about saving nanoseconds per a thousand-iterations loop. This makes no sense from the performance point of view.</em></p>
</blockquote>
<p>And:</p>
<blockquote>
<p><em>These are nearly Identical in performance. Even if the loop does nothing, so that the time spent in the loop is all spent incrementing i and checking its value, it is STILL hard to detect the performance difference. And if you do anything of substance in this loop, the time spent checking against someArray.length is dwarfed by the loop body. This is a stupid complaint.</em></p>
</blockquote>
<p>I have always blindly assumed that the performance hit was due to the interpreter calculating the .length value each time it is referenced, but after talking to some javascript folk (#javascript irc.freenode.net), I discovered that .length is actually a stored value.  Since JavaScript doesn&#8217;t need to re-calculate it on every iteration of the loop, where would the performance hit come from?  Anyway, I thought it would be fun to run some benchmarks of my own to see the difference.  Below is little script I put together, but please take it as a grain of salt because <a href="http://ejohn.org/blog/accuracy-of-javascript-time/" class="blank">JavaScript time is not accurate</a>.</p>
</pre>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> array <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> start<span style="color: #339933;">,</span> diff<span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> results <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> nocache<span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> cached<span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// build array to loop over</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">1000000</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	array<span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> x<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// run tests 25 times</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> x<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> x <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">25</span><span style="color: #339933;">;</span> x<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// length not cached</span>
	start <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> y<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> y <span style="color: #339933;">&lt;</span> array.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> y<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
	results.<span style="color: #660066;">nocache</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> start<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// length cached</span>
	start <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> y<span style="color: #339933;">=</span>0<span style="color: #339933;">,</span> len<span style="color: #339933;">=</span>array.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> y <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> y<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
	results.<span style="color: #660066;">cached</span><span style="color: #009900;">&#91;</span>x<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> start<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// output results</span>
document.<span style="color: #000066; font-weight: bold;">write</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">'&lt;p&gt;No cache time: '</span> <span style="color: #339933;">+</span> avg<span style="color: #009900;">&#40;</span>results.<span style="color: #660066;">nocache</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">' Values: '</span> <span style="color: #339933;">+</span> results.<span style="color: #660066;">nocache</span>.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">','</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">''</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
document.<span style="color: #000066; font-weight: bold;">write</span><span style="color: #009900;">&#40;</span> <span style="color: #3366CC;">'&lt;p&gt;Cached time: '</span> <span style="color: #339933;">+</span> avg<span style="color: #009900;">&#40;</span>results.<span style="color: #660066;">cached</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">' Values: '</span> <span style="color: #339933;">+</span> results.<span style="color: #660066;">cached</span>.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">','</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&lt;/p&gt;'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// logic from http://javascript.about.com/library/blaravg.htm</span>
<span style="color: #003366; font-weight: bold;">function</span> avg<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> av <span style="color: #339933;">=</span> 0<span style="color: #339933;">,</span> cnt <span style="color: #339933;">=</span> 0<span style="color: #339933;">,</span> e<span style="color: #339933;">,</span> len <span style="color: #339933;">=</span> arr.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		e <span style="color: #339933;">=</span> <span style="color: #339933;">+</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>e <span style="color: #339933;">&amp;&amp;</span> arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!==</span> <span style="color: #CC0000;">0</span> <span style="color: #339933;">&amp;&amp;</span> arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">!==</span> <span style="color: #3366CC;">'0'</span><span style="color: #009900;">&#41;</span> e<span style="color: #339933;">--;</span>
		<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> e<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> av <span style="color: #339933;">+=</span> e<span style="color: #339933;">;</span> cnt<span style="color: #339933;">++;</span> <span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">return</span> av<span style="color: #339933;">/</span>cnt<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The code first builds an array with 1,000,000 items, records the execution time of looping over the array 25 times using both methods, and then figures the average.  <a href="/examples/length_cache/chart.jpg">Here are the results:</a></p>
<p class="center"><a href="/examples/length_cache/chart.jpg"><img src="/examples/length_cache/chart.jpg" alt="" style="width:600px" /></a></p>
<p>The results are what I expected except in the Windows versions of Firefox 3.5.2/3.5.5. In all other browsers I tested it is faster to cache the .length value, but in FF3.5 for Windows it is actually faster not to cache.  Internet Explorer receives the most benefit with a ~30% increase in performance when caching, with Opera (Linx) and Chrome (Linux) in fourth and fifth place respectively.  The amount of time is indeed negligible, but every millisecond counts, right?</p>
<p>If nothing else it is interesting to see how long it takes different browsers to loop through a large array.  Firefox and Safari FTW!</p>
</pre>


<p>Related posts:<ol><li><a href='http://www.erichynds.com/jquery/jquery-and-performance-what-is-this/' rel='bookmark' title='Permanent Link: jQuery and Performance: What is &#8216;this&#8217;?'>jQuery and Performance: What is &#8216;this&#8217;?</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
