<?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>unscriptable.com &#187; performance</title>
	<atom:link href="http://unscriptable.com/category/javascript/performance/feed/" rel="self" type="application/rss+xml" />
	<link>http://unscriptable.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Thu, 02 Feb 2012 03:05:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>What is the fastest way to load AMD modules?</title>
		<link>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/</link>
		<comments>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 03:13:44 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=735</guid>
		<description><![CDATA[The AMD format for JavaScript modules was created to allow devs to write elegant, modular code rather than the silly global, name-spaced hackfest we've been writing.  However, AMD has a hidden benefit: it allows modules to be downloaded in parallel, rather than sequentially.  This is a potentially huge performance win.  

However, does this really matter for production code?]]></description>
			<content:encoded><![CDATA[<p>The AMD format for JavaScript modules was created to allow devs to write elegant, modular code rather than the silly global, name-spaced hackfest we&#8217;ve been writing.  However, AMD has a hidden benefit: it allows modules to be downloaded in parallel, rather than sequentially.  This is a potentially huge performance win.  </p>
<p>However, does this really matter for production code?<br />
<span id="more-735"></span></p>
<h2>Blocking before Loading</h2>
<p>Virtually all of the examples of AMD code out on the web look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;script src=&quot;some-amd-loader.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
someAmdLoader([&quot;moduleA&quot;, &quot;moduleB&quot;, &quot;domReady!&quot;], function (A, B) {
    var app = new A(), boot = new B(app);
    boot.init();
});
&lt;/script&gt;</pre></div></div>

<p>In this example, we&#8217;re loading moduleA and moduleB in parallel.  This is the fast way to do it, right?  Yes, but also note that we&#8217;re loading some-amd-loader.js in a blocking fashion.  The second script element (and the rest of the document) has to wait for some-amd-loader.js to finish loading and executing before proceeding.</p>
<p>This isn&#8217;t ideal, of course.  So how do we fix this?</p>
<p>Answer: by only including one script element in the page and ensuring that that single script allows the page to continue parsing and rendering.</p>
<h2>Native async loading</h2>
<p>Here&#8217;s what we really want:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;script src=&quot;myapp-bootstrap.js&quot; defer async=&quot;true&quot;&gt;&lt;/script&gt;</pre></div></div>

<p>Newer browsers support the async attribute.  <code>async="true"</code> instructs the browser that it can proceed to parse and evaluate any future script elements without waiting.  You&#8217;d think a browser would notice that there&#8217;s only one script element, right?  Just in case, we&#8217;re going to tell it how we want it to behave. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Older browsers don&#8217;t support the async attribute.  However, they do support the defer attribute.  This attribute tells the browser that it may defer execution of the script until a convenient time &#8212; even after the body is rendered.  Unfortunately, browsers don&#8217;t all act the same with this attribute.  Most browsers, though, do a fairly good job when there&#8217;s only one script element in the document.</p>
<p>Since the browser isn&#8217;t waiting for the script&#8217;s javascript to load or execute, the script element can be in the head where it belongs.  There is no need to put it at the ned of the body element.  </p>
<p>So, what&#8217;s myapp-bootstrap.js look like in this scenario?  The sky&#8217;s the limit, but you can imagine a minimal set of requirements:</p>
<p>1. it contains an AMD loader<br />
2. it contains one of the following:<br />
    a. instructions to load the rest of the app<br />
    b. the actual code for the rest of the app</p>
<p>If you&#8217;re compiling/optimizing your AMD modules into a single js file already, it&#8217;s not too much harder to concatenate the actual AMD loader onto the front of the file (using requirements 1 and 2b above).  Some compilers/optimizers have support for this built in, <a href="http://requirejs.org">RequireJS</a>, for example.  RequireJS also has a companion loader, <a href="http://github.com/jrburke/almond">almond</a>, that is tiny and can handle the simpler environment inside a compiled file.</p>
<p>So, essentially, all that AMD provided for us in this single-script scenario is a way to ensure ordering of our modules into a single file, it seems.  Does this mean that the whole async loading behavior we&#8217;ve been touting about AMD is just a bunch of &#8220;<a href="http://github.com/paulirish/html5-boilerplate/issues/28#issuecomment-1773156">snake oil</a>&#8220;?  Not at all.  Keep reading:</p>
<h2>We ain&#8217;t oiling no snakes</h2>
<p>Let&#8217;s say our web app has several pages.  Each of these pages has a core set of modules it requires to function and a set of modules that are unique to it.  This is not an unlikely scenario, and is quite likely the most common case.  </p>
<p>In this scenario, it could be ideal to allow the common core modules to be fetched from cache and the unique, page-specific modules to be loaded separately.  Each subsequent page load would be fast because it&#8217;s not loading as much code.  For this scenario, requirements 1 and 2a are the best choice.  The code inside the single file would look a lot like the original code snippet above:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// loader source code goes here</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// initialize our app in two parts!</span>
someAmdLoader<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;moduleA&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;moduleB&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;domReady!&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>A<span style="color: #339933;">,</span> B<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> app <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> A<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> boot <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> B<span style="color: #009900;">&#40;</span>app<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    boot.<span style="color: #660066;">init</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>How finely grained you break up your app is totally unique to your app and your target browsers.  If you are targeting older IE&#8217;s, then your app is burdened by limited HTTP requests.  A small number of fetches per page is best.  </p>
<p>More sophisticated apps or ones that can ignore older browsers may be able to take advantage of multiple parallel downloads.  However, you must remember that each image, css file, and xhr consumes an HTTP request!</p>
<p>Most of the apps I write have a very sparse body because the UI is built by templates embedded in the javascript.  The css is embedded, too (via <a href="http://github.com/unscriptable/curl">curl.js</a>&#8216;s css! plugin and the <a href="http://github.com/unscriptable/cram">cram</a> optimization tool).  This means we can break the app up into several files.  Some of these files are loaded when the page loads.  Others are loaded when needed (&#8220;lazily&#8221;).</p>
<p>Do some experimentation to figure out what your ideal situation is.  If you already have, please share it with the rest of us in the comments section!  There are other ways we could load modules since AMD is very flexible.  Do you have an entirely different approach?  </p>
<p>Thanks!</p>
<p>&#8211; John</p>
<p><strong>[update 2011-09-22 12:35 PM EDT]</strong> @getify says that he doesn&#8217;t recommend the &#8220;defer&#8221; attribute due to jQuery/FF3.x issues. see twitter convo <a href="http://twitter.com/getify/status/116879861175422976">here</a>.  Also: &#8220;defer&#8221; isn&#8217;t always what you want.  Use wisely. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>curl.js &#8211; yet another AMD loader [updated]</title>
		<link>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/</link>
		<comments>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 01:24:33 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[cujo.js]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[l10n]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=698</guid>
		<description><![CDATA[Over the past several weeks, I&#8217;ve been writing an AMD-compatible javascript loader called curl.js. AMD stands for Asynchronous Module Definition and is a CommonJS proposed standard for writing javascript modules. The module format closely follows the proposed migration path set out by ECMA&#8217;s proposed ES-Harmony javascript modules. curl stands for Cujo Resource Loader since it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past several weeks, I&#8217;ve been writing an AMD-compatible javascript loader called <a href="https://github.com/unscriptable/curl">curl.js</a>. AMD stands for Asynchronous Module Definition and is a <a href="http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition">CommonJS proposed standard</a> for writing javascript modules.  The module format closely follows the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:modules">proposed migration path</a> set out by ECMA&#8217;s proposed ES-Harmony javascript modules.</p>
<p>curl stands for <em>Cu</em>jo <em>R</em>esource <em>L</em>oader since it&#8217;s an integral part of the re-engineering of <a href="http://cujojs.com">cujo.js</a>.</p>
<p>An AMD-compatible javascript loader is (surprise, surprise) an asynchronous javascript loader that is savvy about AMD-formatted javascript modules.</p>
<p><strong>[update]</strong><br />
Version 0.3.2 is out! <a href="https://github.com/unscriptable/curl">fork it!</a></p>
<p><span id="more-823"></span></p>
<h1>What is an asynchronous loader?</h1>
<p>Web apps, especially large ones, require many modules and resources. Most of these modules and resources need to be loaded at page load, but some may be loaded later, either in the background or &#8220;just in time&#8221;. They also need to be loaded as quickly as possible.</p>
<p>The traditional way to load javascript modules is via a <code>&lt;SCRIPT&gt;</code> element in an HTML page. Similarly, CSS files are loaded via a <code>&lt;LINK&gt;</code> element, and text resources are either loaded in the page or via XHR calls.</p>
<p>The problem with <code>&lt;SCRIPT&gt;</code> and <code>&lt;LINK&gt;</code> elements is that a browser must execute them sequentially since it has no idea if one may depend on another. It just assumes the developer has placed them in the correct order and that there are dependencies. (The term &#8220;synchronous loading&#8221; is used to describe this process since the elements are executed in a single timeline. I think &#8220;sequential&#8221; is a much better word, but nobody asked me.)</p>
<p>If there are no dependencies between two files, loading them sequentially is a waste of time. These files could be loaded and executed in parallel (i.e at the same time).</p>
<p>An asynchronous loader does just that: it loads javascript files (and other types of files) in parallel as much as possible.</p>
<p>curl.js has lots of company. Other async loaders include LABjs, Steal.js, yepnope.js, $script.js, bdLoad, and RequireJS.</p>
<p>(<a href="https://spreadsheets.google.com/ccc?key=0Aqln2akPWiMIdERkY3J2OXdOUVJDTkNSQ2ZsV3hoWVE&amp;hl=en#gid=2">a more complete list can be found here</a>)</p>
<h1>What is AMD?</h1>
<p>Asynchronous Module Definition is the CommonJS proposed standard for javascript modules that can be loaded by asynchronous loaders. It defines a simple API that developers can use to write their javascript modules so that they may be loaded by any AMD-compliant loader.</p>
<p>The AMD proposal follows the <a href="http://wiki.commonjs.org/wiki/Modules/1.1">CommonJS Modules proposal</a> as much as possible. Because of the way browsers load and evaluate scripts, AMD can&#8217;t follow it completely without causing significant processing overhead (think serious regex action and eval()). Instead, AMD allows us to place a lightweight wrapper around javascript modules to help work around the shortcomings.</p>
<p>Ultimately, both proposals (AMD and Modules 1.1) are in preparation for an official javascript modules specification and eventual implementation in browsers. (Hopefully!)</p>
<p>If you don&#8217;t want to wait for official javascript modules, then don&#8217;t. The future is now. AMD works now &#8212; and it&#8217;s awesome.</p>
<p>AMD&#8217;s API focuses on two globally-available functions: <code>require()</code> and <code>define()</code>. <code>require()</code> specifies a list of dependent modules or resources that must be loaded before running a set of code. This code resides in a callback function that is executed asynchronously, i.e. it runs later, not in the current &#8220;thread&#8221;. Specifically, it executes when all of the dependencies are loaded and ready.</p>
<p>Actually, the proposal says that the <code>require()</code> function could have a different name &#8212; or could even be implemented differently. To keep with convention &#8212; and to better integrate with non-AMD CommonJS modules &#8212; we&#8217;re using <code>require()</code>, but <code>curl()</code> is also an alias to <code>require()</code>.</p>
<p>It&#8217;s more important that the <code>define()</code> method be consistent. This is the method that tells the loader what modules have been loaded by a script. <code>define()</code> also specifies a list of dependencies and a callback function that defines and/or creates the resource when the dependencies are ready. Optionally, <code>define()</code> also takes a name parameter, but this is mainly for build tools and optimizers.</p>
<p>AMD&#8217;s API also helps code reuse by providing compatibility with CommonJS server modules. AMD-compliant loaders support the same <code>require()</code> syntax and argument signatures as server-side javascript (ssjs) modules.</p>
<p>Not all async loaders are AMD-compliant. Of the list above, only the following are AMD-compliant:</p>
<p>curl.js <a href="http://github.com/unscriptable/curl">http://github.com/unscriptable/curl</a></p>
<p>RequireJS <a href="http://requirejs.org/">http://requirejs.org/</a></p>
<p>bdLoad <a href="http://bdframework.org/bdLoad">http://bdframework.org/bdLoad</a></p>
<p>(there are a few others in that google spreadsheet link)</p>
<p>The beauty of AMD loaders is their ability to remove the drudgery of manually managing dependencies. Since all dependencies are listed within the modules, the loader will ensure that everything is loaded into the browser &#8212; and in the right order.</p>
<p>Even better: the modules are always loaded in parallel without blocking the loading process of the rest of the page.</p>
<p>Most of the current AMD loaders also support plugins. Plugins allow you to load CSS, HTML templates, i18n/L10n bundles, CSS generated from LESS, plain vanilla javascript files, etc.  Again, these are loaded without blocking so the performance is optimal.</p>
<h1>So how can I get my hands on curl.js?</h1>
<p><a href="https://github.com/unscriptable/curl">curl.js</a> is up on github!  Fork it or clone it to your local disk and check out the Very Simple Example in the README file.  </p>
<p>At the time of this blog post, curl.js is at version 0.3.1 and is not 100% compatible with CommonJS Modules 1.1 (only missing the <code>exports</code> and <code>module</code> parameters).  However, I am currently unit-testing 0.3.2, which is 100% compatible!  </p>
<p>Compared to other AMD loaders, curl.js is <strong>tiny</strong>.  At 4.5KB (2.1KB gzipped using Google Closure Compiler), it&#8217;s half the size of the others.  It also employs some wicked cool techniques using <a href="http://wiki.commonjs.org/wiki/Promises">promises</a>.</p>
<p>Version 0.3.2 will be ready for production use, despite the <em>zero-dot</em> version number.  Please check it out and let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deduplicate any array in Javascript</title>
		<link>http://unscriptable.com/2009/12/08/deduplicate-any-array-in-javascript/</link>
		<comments>http://unscriptable.com/2009/12/08/deduplicate-any-array-in-javascript/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 05:04:30 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[dojo]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=467</guid>
		<description><![CDATA[As part of an ongoing project, I had to deduplicate a potentially large array of nodes.  ...  It seemed every other implementation used the hash map method and only worked on limited data types.  I hate writing the same code twice (unless it's to improve it), so I decided to write something that works with any data type.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve neglected this blog lately.  My only excuse is that I am <em>very, very busy</em>! Not only have I been lucky enough to land a great opportunity working with some very bright jQuery Interactive Developers at <a href="http://www.molecular.com/">Molecular</a>, but I&#8217;ve also been working on <strong>something really big</strong>.  (More on that later!)</p>
<p>But despite being busy, I felt compelled to post this one. As part of the <strong>something really big</strong> project, I had to <a href="http://en.wikipedia.org/wiki/Data_deduplication">deduplicate</a> a potentially large array of nodes.  Dojo doesn&#8217;t have a built-in function for deduplication (a.k.a &#8220;deduping&#8221;).  How could it not?  Doesn&#8217;t everybody have to do this once in a while?  </p>
<p><em>I guess I&#8217;ll have to write one.  How hard could it be?</em><br />
<span id="more-467"></span><br />
It wasn&#8217;t because dojo didn&#8217;t implement a deduping method that I felt compelled.  No, it was the series of events after I wrote my own version.  Just after I finished it, one of those smart IDevs at Molecular shared his recent hash map-based implementations that worked only with numbers.  Then I noticed that jQuery has a deduping method, <code>unique()</code>.  However, it only deduplicates DOM Nodes.  </p>
<p>Finally, I ran across this blog <a href="http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates">post</a> that uses the hash-map method and works only on strings.  (Actually, it works on any objects that return unique values from their toString() methods, but that&#8217;s not as common as you&#8217;d think in Javascript. For example, object literals typically return &#8220;[Object object]&#8221; from the toString() method.)</p>
<p>It seemed every other implementation used the hash map method and only worked on limited data types.  I hate writing the same code twice (unless it&#8217;s to improve it), so I decided to write something that works with any data type.  </p>
<p><strong><em>One function to rule them all!</em> (No! Don&#8217;t even go there&#8230;!)</strong></p>
<p>I probably should have done some research before diving in, but that&#8217;s not how I roll.  (Where&#8217;s the challenge in that?)  From previous experience I already knew of at least two ways to do it: a) keeping a hash map of the values (hash map method), or b) pre-sorting the values.  The former method (hash map) seemed slower and more memory intensive, so I forged ahead with the second method (pre-sorting).</p>
<p>The pre-sort method works like this:</p>
<ol>
<li>sort the data items in the array</li>
<li>loop through the sorted data items:</li>
<li>compare each of the data items to the previous one</li>
<li>if the previous is the same as the current, don&#8217;t add the current item to the output array</li>
</ol>
<p><em>Simple enough!</em></p>
<p>Here&#8217;s the code using dojo to wrap the Javascript 1.6 Array iterators:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">    <span style="color: #003366; font-weight: bold;">function</span> dedup <span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/* Array */</span> array<span style="color: #339933;">,</span> <span style="color: #009966; font-style: italic;">/* Function */</span> compareFunc<span style="color: #339933;">,</span> <span style="color: #009966; font-style: italic;">/* Object? */</span> context<span style="color: #339933;">,</span> <span style="color: #009966; font-style: italic;">/* Boolean? */</span> preemptive<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">//  summary: removes duplicate items from an array. compareFunc should behave</span>
        <span style="color: #006600; font-style: italic;">//      exactly like the lambda function used in array.sort(), returning:</span>
        <span style="color: #006600; font-style: italic;">//       0 - if the two items to compare are equivalent</span>
        <span style="color: #006600; font-style: italic;">//      -1 - if the first item should be sorted to an earlier position than the second</span>
        <span style="color: #006600; font-style: italic;">//       1 - if the first item should be sorted to a later position than the second</span>
        <span style="color: #006600; font-style: italic;">//      Returns an array with no duplicates.</span>
        <span style="color: #006600; font-style: italic;">//      Note: items found later in the array are favored over earlier items. This means</span>
        <span style="color: #006600; font-style: italic;">//      that if am earlier item is found to be a duplicate of an later item, it is not</span>
        <span style="color: #006600; font-style: italic;">//      included in the returned array.  You might ask, &quot;Who cares which one is favored?&quot;</span>
        <span style="color: #006600; font-style: italic;">//      Glad you asked! It depends upon how you define &quot;duplicate&quot;. If you wanted to</span>
        <span style="color: #006600; font-style: italic;">//      remove all nodes with duplicate ids, you could supply a compareFunc that inspected</span>
        <span style="color: #006600; font-style: italic;">//      node ids.  The nodes are not identical in this case, just the ids.</span>
        <span style="color: #006600; font-style: italic;">//      If you wish to favor the earlier items, set preemptive = true;</span>
        <span style="color: #006600; font-style: italic;">//      Note: undefined values are omitted from the output array.</span>
        <span style="color: #006600; font-style: italic;">//  array: Array - the array to be deduped</span>
        <span style="color: #006600; font-style: italic;">//  compareFunc: Function - see above</span>
        <span style="color: #006600; font-style: italic;">//  context: Object - context on which to run compareFunc (i.e. the &quot;this&quot; reference from</span>
        <span style="color: #006600; font-style: italic;">//      within compareFunc). defaults to null/window</span>
        <span style="color: #006600; font-style: italic;">//  preemptive: Boolean - set to true to favor earlier occuring items (see above)</span>
        <span style="color: #003366; font-weight: bold;">var</span> comparator <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: #000066; font-weight: bold;">return</span> compareFunc.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
            prev<span style="color: #339933;">,</span>
            keepers <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #006600; font-style: italic;">// by first sorting the array, we know that dups will be adjacent to each other</span>
        dojo.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span>array.<span style="color: #660066;">sort</span><span style="color: #009900;">&#40;</span>comparator<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> pos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #000066; font-weight: bold;">item</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">'undefined'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> prev <span style="color: #339933;">==</span> <span style="color: #3366CC;">'undefined'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #006600; font-style: italic;">// is the previous item different from this one?</span>
                    <span style="color: #003366; font-weight: bold;">var</span> eq <span style="color: #339933;">=</span> comparator<span style="color: #009900;">&#40;</span>prev<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
                    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>preemptive<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>eq<span style="color: #009900;">&#41;</span>
                            keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// add this one</span>
                    <span style="color: #009900;">&#125;</span>
                    <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>eq<span style="color: #009900;">&#41;</span>
                            keepers.<span style="color: #660066;">pop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// remove prev one</span>
                        keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// always add current one (it may be deleted in the next iteration)</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                prev <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> dojo.<span style="color: #660066;">map</span><span style="color: #009900;">&#40;</span>keepers<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> array<span style="color: #009900;">&#91;</span>pos<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The dedup() method requires an array (duh) and a comparison function (compareFunc).  The comparison function is exactly the same function you&#8217;d pass to sort an array.  Note that it&#8217;s run twice: once to sort the array and once to test if the previous value is the same as the current value.</p>
<p>The context parameter is useful if you need to pull in other data for compareFunc to do its job in the context of some object.  For even more control over which duplicate instances are kept, you can use the preemptive parameter.  Set this to true to keep items that occur earlier in the array.</p>
<p>I can see some people scratching their heads. <em>Why does it matter which item we keep if they&#8217;re duplicates of each other?</em>  Well, nobody said they had to be <em>exact</em> duplicates!  For instance, maybe you want to reduce a table&#8217;s rows to only the ones that have unique integer values in their first cell.</p>
<p>And here&#8217;s how you&#8217;d do that (error-checking omitted for brevity):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> myDedupedRows <span style="color: #339933;">=</span> dedup<span style="color: #009900;">&#40;</span>myTable.<span style="color: #660066;">rows</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>rowA<span style="color: #339933;">,</span> rowB<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// it's important to use a comparison that works correctly in Array sort() for best efficiency!</span>
    <span style="color: #000066; font-weight: bold;">return</span> parseInt<span style="color: #009900;">&#40;</span>rowA.<span style="color: #660066;">cells</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">innerHTML</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> parseInt<span style="color: #009900;">&#40;</span>rowB.<span style="color: #660066;">cells</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">innerHTML</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>That&#8217;s pretty simple if you are already comfortable with writing lambda functions for the sort method, of course.</p>
<p>Deduping numbers:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> uniques <span style="color: #339933;">=</span> dedup<span style="color: #009900;">&#40;</span>arrayOfNumberIDs<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>idA<span style="color: #339933;">,</span> idB<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> idA <span style="color: #339933;">-</span> idB<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>Deduping object instances:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> uniques <span style="color: #339933;">=</span> dedup<span style="color: #009900;">&#40;</span>myObjects<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>objA<span style="color: #339933;">,</span> objB<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// this works for numbers, strings, dates... but don't mix types!</span>
    <span style="color: #000066; font-weight: bold;">return</span> objA.<span style="color: #660066;">keyProperty</span> <span style="color: #339933;">-</span> objB.<span style="color: #660066;">keyProperty</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>Deduping object instances that have multiple key properties:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> uniques <span style="color: #339933;">=</span> dedup<span style="color: #009900;">&#40;</span>myObjects<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>objA<span style="color: #339933;">,</span> objB<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> test <span style="color: #339933;">=</span> objA.<span style="color: #660066;">keyProperty</span> <span style="color: #339933;">-</span> objB.<span style="color: #660066;">keyProperty</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>test <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// keyProperty is the same, so dig deeper</span>
        <span style="color: #000066; font-weight: bold;">return</span> objA.<span style="color: #660066;">altKey</span> <span style="color: #339933;">-</span> objB.<span style="color: #660066;">altKey</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
        <span style="color: #000066; font-weight: bold;">return</span> test<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>Deduping numbers the safe way:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> uniques <span style="color: #339933;">=</span> dedup<span style="color: #009900;">&#40;</span>arrayOfNumberIDs<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>idA<span style="color: #339933;">,</span> idB<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// force to numbers in case we have strings by accident</span>
    <span style="color: #000066; font-weight: bold;">return</span> parseFloat<span style="color: #009900;">&#40;</span>idA<span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> parseFloat<span style="color: #009900;">&#40;</span>idB<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>At first glance, the pre-sort method looks more complex than the hash map methods, but it&#8217;s really not.  Once you take out the code that skips undefined values (like all good <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6">array iterators</a> should) and the code to allow the preemptive functionality, it&#8217;s only a line or two longer.</p>
<p>How about memory usage?  Hm.  My assumption that my method would use less memory wasn&#8217;t as accurate as I thought.  In the hash map methods, a temporary array and a hash-map of the non-redundant values are created.  In my pre-sort method, a complete copy of the original array and a copy of the deduped array are created.  This could go either way, depending on how large the original array is and on how Javascript engines internally manage hash maps (object literals, actually), but it&#8217;s likely that the pre-sort has a larger memory footprint.  (It&#8217;s likely that the Javascript engines create internal data structures to speed-up property look-ups on object literals.  However, it&#8217;s certain that the engines pre-allocate several kilobytes of space for array items. I&#8217;ll bet they allocate a minimum of 16kB per array created.)</p>
<p>Finally, I&#8217;m hesitant to claim any performance prizes, either.  I assume that since the compareFunc is run at least twice for each item in the array, it&#8217;s a performance bottleneck.  The hash map methods don&#8217;t do much in Javascript besides the loops.  The rest is run inside compiled code under the hood of the Javascript engine.  </p>
<p><strong>But maybe that&#8217;s the price for creating a function that dedups anything?</strong></p>
<p>I&#8217;m too <del datetime="2009-12-08T03:53:13+00:00">lazy</del> busy to test any of my assumptions, but if you are intrigued or bored, please have at it!  </p>
<p>And be sure to post any feedback! Did I miss something?  Did I make a stoopid mistake?   Can you write a version that falls back to the hash map method when using simple data types (and therefore doesn&#8217;t need compareFunc)?  </p>
<p>What? You don&#8217;t use dojo?!?! <img src='http://unscriptable.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   A jQuery port should be brain-dead simple (s/dojo.forEach/$.each/ and s/dojo.map/$.map/).  Here&#8217;s a version that replaces the dojo calls with Javascript 1.6 array iterators.   (Note: Javascript 1.6 array iterators work in recent browsers only!)</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">    <span style="color: #003366; font-weight: bold;">function</span> dedup <span style="color: #009900;">&#40;</span>array<span style="color: #339933;">,</span> compareFunc<span style="color: #339933;">,</span> context<span style="color: #339933;">,</span> preemptive<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> comparator <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: #000066; font-weight: bold;">return</span> compareFunc.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
            prev<span style="color: #339933;">,</span>
            keepers <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        array.<span style="color: #660066;">sort</span><span style="color: #009900;">&#40;</span>comparator<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">forEach</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: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> pos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> <span style="color: #000066; font-weight: bold;">item</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">'undefined'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> prev <span style="color: #339933;">==</span> <span style="color: #3366CC;">'undefined'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003366; font-weight: bold;">var</span> eq <span style="color: #339933;">=</span> comparator<span style="color: #009900;">&#40;</span>prev<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
                    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>preemptive<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>eq<span style="color: #009900;">&#41;</span>
                            keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                    <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>eq<span style="color: #009900;">&#41;</span>
                            keepers.<span style="color: #660066;">pop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        keepers.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                prev <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> keepers.<span style="color: #660066;">map</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>pos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> array<span style="color: #009900;">&#91;</span>pos<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/12/08/deduplicate-any-array-in-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A Better Javascript Un-memoizer. Part 1: Epic FAIL!</title>
		<link>http://unscriptable.com/2009/05/07/a-better-javascript-un-memoizer-part-1-epic-fail/</link>
		<comments>http://unscriptable.com/2009/05/07/a-better-javascript-un-memoizer-part-1-epic-fail/#comments</comments>
		<pubDate>Fri, 08 May 2009 02:51:10 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=332</guid>
		<description><![CDATA[In my previous post, A Better Javascript Memoizer, some of you left some great feedback. (Thanks to all of you!) I think it&#8217;s because each of us has a different definition of &#8220;better&#8221;. That makes sense. Actually, I just wrote that title quickly when I got inspired to start writing. Just before publication, I was [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post, <a href="http://unscriptable.com/index.php/2009/05/01/a-better-javascript-memoizer/">A Better Javascript Memoizer</a>, some of you left some great feedback.  (Thanks to all of you!) I think it&#8217;s because each of us has a different definition of &#8220;better&#8221;.  That makes sense.  </p>
<p>Actually, I just wrote that title quickly when I got inspired to start writing.  Just before publication, I was going to change it to remove the word &#8220;better&#8221;.  But as an experiment, I decided to keep it to see if it would elicit more feedback.  Success!  <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Two people wanted to investigate cache invalidation, a.k.a. &#8220;unmemoization&#8221;, some more.  Scratch that.  Make that three people: I wanted to try it, too.  </p>
<p>Here&#8217;s my attempt at better unmemoization in Javascript.  I&#8217;m looking forward to more great feedback!  (I really, really need it this time!)<br />
<span id="more-332"></span></p>
<p>First, let&#8217;s simplify the memoize function a bit.  In my haste to publish, I missed a good opportunity to increase the performance by using a local variable.  I also found a way to shorten it and increase readability by reducing the simplistic <code>if</code> statements into single-line statements using the conditional operator (?:). Here&#8217;s the updated version:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> memoize <span style="color: #009900;">&#40;</span>func<span style="color: #339933;">,</span> context<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> memoizeArg <span style="color: #009900;">&#40;</span>argPos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</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> arg <span style="color: #339933;">=</span> arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// new local variable</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> func.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> memoizeArg<span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> memoizeArg<span style="color: #009900;">&#40;</span>func.<span style="color: #660066;">length</span> <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This looks <em>better</em> to my eyes &mdash; although the cache assignments are somewhat hidden in the last operand of the conditional operator. (Doh! Bad programmer, bad!)  Oh, and look!  I succumbed to the func.length precedence over func.arity as noted by igstan on <a href="http://ajaxian.com/archives/a-better-javascript-memoizer#comments">Ajaxian</a>.</p>
<h2>Scheduled whole-cache reset</h2>
<p>If you looked at any of the unmemoize features in the links from the previous post or at Dave&#8217;s code snippet in the comments, you&#8217;ll see that there are [at least] two ways to reset the cache: at an explicit time (scheduled), and just-in-time (JIT). Scheduled reset uses the <code>setTimeout</code> function and JIT uses date math.</p>
<p>Here&#8217;s an example of scheduled reset.  It resets the entire cache after a given delay after its first use.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// whole-cache reset via setTimeout</span>
<span style="color: #003366; font-weight: bold;">function</span> memoize2 <span style="color: #009900;">&#40;</span>func<span style="color: #339933;">,</span> context<span style="color: #339933;">,</span> <span style="color: #009966; font-style: italic;">/* msec */</span> cacheLifetime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> memoizeArg <span style="color: #009900;">&#40;</span>argPos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #006600; font-style: italic;">// reset the cache after the specified timeout:</span>
        setTimeout<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> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> cacheLifetime<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</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> arg <span style="color: #339933;">=</span> arguments<span style="color: #009900;">&#91;</span>argPos<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>argPos <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> func.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> memoizeArg<span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> memoizeArg<span style="color: #009900;">&#40;</span>func.<span style="color: #660066;">length</span> <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Wow.  This is really ill-conceived.  The first cache to be created (let&#8217;s call it the root cache) is the first one destroyed.  Since all other caches (for the other parameters) are reachable <em>hierarchically</em> through the root cache, they&#8217;re unreachable as soon as the root cache is destroyed.  Therefore, we&#8217;ll potentially have several unreachable caches wasting memory until their setTimeouts execute (which could be as much as cacheTimeout msec later).  </p>
<p>If it&#8217;s not immediately apparent to you why this is true (and it wasn&#8217;t for me), then note that there are now two function closures with a reference to the local cache variable: 1) the returned function, and 2) the anonymous function in the setTimeout (a.k.a. &#8220;setTimeout function&#8221;).  When a higher-level cache is reset/released via its &#8220;setTimeout function&#8221;, the references to the lower-level caches (via the returned functions from the calls to memoizeArg()) are released.  However, the references to the lower-level caches from their corresponding &#8220;setTimeout functions&#8221; are not released until those setTimeouts execute!  </p>
<p><strong>Strike one!</strong></p>
<p>(If you&#8217;re not experienced in functional programming, this is probably very confusing.  Either that, or my explanations need a lot more work.)</p>
<h2>Scheduled reset of individual cache entries</h2>
<p>OK.  What about if we invalidate individual cache items instead of whole caches?  Would that fix the situation?  Lets see:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// cache entry reset via setTimeout (each entry times out individually)</span>
<span style="color: #003366; font-weight: bold;">function</span> memoize3 <span style="color: #009900;">&#40;</span>func<span style="color: #339933;">,</span> context<span style="color: #339933;">,</span> <span style="color: #009966; font-style: italic;">/* msec */</span> cacheLifetime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> memoizeArg <span style="color: #009900;">&#40;</span>argPos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</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> arg <span style="color: #339933;">=</span> arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #006600; font-style: italic;">// schedule this cache entry for deletion if it's our first time</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>arg <span style="color: #000066; font-weight: bold;">in</span> cache<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                setTimeout<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: #000066; font-weight: bold;">delete</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> cacheLifetime<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> func.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">return</span> arg <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> cache<span style="color: #009900;">&#91;</span>arg<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> memoizeArg<span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> memoizeArg<span style="color: #009900;">&#40;</span>func.<span style="color: #660066;">length</span> <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>There!  Fixed!  Um&#8230;right?</p>
<p>Not really.  We&#8217;ve got the same exact problem: all of the anonymous functions in the setTimeouts (again, &#8220;setTimeout functions&#8221;) are holding references to our caches!  Even though our cache entries will get cleaned up one entry at a time sooner, they&#8217;ll still be wasting memory for a while.  </p>
<p>Furthermore, there will be hundreds or thousands of active setTimeouts when there are a hunreds or thousands of values to cache.  I haven&#8217;t done any formal testing, but I&#8217;ll wager that this creates a <strong>bad situation</strong> in some browsers / environments.  (Yes, I&#8217;m looking at you, IE 6!)</p>
<p><strong>Strike Two!</strong></p>
<h2>Reset the cranium</h2>
<p>This is really bothering me.  It&#8217;s the recursion and closures that are causing the problem!  And those are the very things I set out to utilize to make a &#8220;better&#8221; memoizer!  </p>
<p>It&#8217;s time to reset my cranium rather than <strong>strike out</strong>.  Lots of ideas are coming in to my head, but none of them feel right.  None of them deserve the word, &#8220;better&#8221;.  Not to me, anyways.</p>
<p>If you have some suggestions, please let me know!  </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/05/07/a-better-javascript-un-memoizer-part-1-epic-fail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Better Javascript Memoizer</title>
		<link>http://unscriptable.com/2009/05/01/a-better-javascript-memoizer/</link>
		<comments>http://unscriptable.com/2009/05/01/a-better-javascript-memoizer/#comments</comments>
		<pubDate>Sat, 02 May 2009 04:08:29 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[memoization javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=272</guid>
		<description><![CDATA[... what struck me was his use of the function instance to cache the results.  In Javascript, functions are first-class objects and can be assigned properties just like any other object.  But should we do this?  It certainly seems like this could cause intractable problems if used widely.  Imagine if everybody started decorating functions and methods with properties?  ... The two-parameter case is quite ugly and unwieldy, in my opinion.  However, it shed some light on a general-purpose solution, a "memoizer" I'd like to call it.  With a little bit of work, I was able to devise a memoizer for any function with explicitly-declared parameters.  Here it is ...]]></description>
			<content:encoded><![CDATA[<p>Last month, I had the pleasure of meeting tons of excellent and intelligent front-end engineers at JSConf 2009 — the conference for Javascript in Washington DC.  If you are a front-end engineer — or even if you write programs in Javascript for back ends, mobile devices, or desktops — you absolutely have to go to JSConf 2010.  It&#8217;s apparent that Javascript is quickly becoming one of the hottest languages for all environments and applications, and JSConf is the first (and only) conference that deals with Javascript exclusively.</p>
<p><a href="http://jsconf2009.com/">JSConf 2009</a></p>
<p><a href="http://www.slideshare.net/tag/jsconf">Track A presentations from JSConf 2009</a></p>
<p>One of the Track A speakers was Stoyan Stefanov, a really smart guy from Yahoo.   His presentation was about high-performance web apps, but on one slide in particular, I was struck by his implementation of memoization (slide 79 of 87) because he used the function instance to cache the results of the function itself.</p>
<p>If you&#8217;re not familiar with memoization, here&#8217;s a great overview:</p>
<blockquote><p>In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.</p></blockquote>
<p><a href="http://en.wikipedia.org/wiki/Memoization">Memoization (Wikipeida)</a></p>
<p>In other words, it&#8217;s a way to cache the results of function calls so that repeated expensive computations or lengthy lookups can be avoided.</p>
<p>Here&#8217;s Stoyan&#8217;s example:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> myFunc<span style="color: #009900;">&#40;</span>param<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>myFunc.<span style="color: #660066;">cache</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        myFunc.<span style="color: #660066;">cache</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>myFunc.<span style="color: #660066;">cache</span><span style="color: #009900;">&#91;</span>param<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> result <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// ...</span>
        myFunc.<span style="color: #660066;">cache</span><span style="color: #009900;">&#91;</span>param<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> result<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> myFunc.<span style="color: #660066;">cache</span><span style="color: #009900;">&#91;</span>param<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>(Use your imagination to fill in some complex or lengthy task in place of the line with the &#8220;…&#8221;!)</p>
<p>Again, what struck me was his use of the function instance to cache the results.  In Javascript, functions are first-class objects and can be assigned properties just like any other object.  But should we do this?  It certainly seems like this could cause intractable problems if used widely.  Imagine if everybody started decorating functions and methods with properties?  (Actually, debuggers such as Drosera and Firebug now use properties on function instances to help identify them in logs and traces.  It seems to me we should try not to invade on that space!)</p>
<p>So, of course, I set out to answer the question, &#8220;Do we really need to use the function instance to hold the result cache?&#8221;</p>
<p>The answer is &#8220;No&#8221;.  It&#8217;s really quite easy to avoid, too.<br />
<span id="more-272"></span></p>
<p>Keep reading if you&#8217;re interested in the steps I took to come to a general purpose solution.  Otherwise, <a href="#gen_sol">click here</a> to go straight to it.</p>
<h2>A simple example</h2>
<p>Here&#8217;s the simplest form: a constant-valued function with one parameter.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// constant-valued function. not very interesting</span>
<span style="color: #003366; font-weight: bold;">var</span> memoizedFunc0 <span style="color: #339933;">=</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> result<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</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;">// in a real-world example this next line would do some</span>
            <span style="color: #006600; font-style: italic;">// complex math instead of just returning a date object</span>
            <span style="color: #000066; font-weight: bold;">return</span> result <span style="color: #339933;">||</span> <span style="color: #009900;">&#40;</span>result <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: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Notice that we use an auto-execute, anonymous function (the outer function) solely to create a closure around the <code>result</code> variable.  Also notice that the variable, <code>memoizedFunc0</code>, is assigned a reference to the inner anonymous function because the outer function executes immediately and returns it.  The inner function is the one that gets executed when <code>memoizedFunc0</code> is called later in our program.</p>
<p>The memoization happens in the inner function&#8217;s <code>return</code> statement.  We&#8217;re using the short-circuit Boolean OR operator (<code>||</code>) to return <code>result</code> if it is assigned.  Of course, during the first execution, the second half of the statement runs (<code>(result = new Date())</code>), assigning a value to <code>result</code>.</p>
<p>Admittedly, this is a very boring example.  Stoyan&#8217;s was much more interesting since the memoized function took a parameter and returned a different result for each possible parameter.  So let&#8217;s take a look at a multi-valued memoized function:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// multi-valued function with string-serializable param</span>
<span style="color: #003366; font-weight: bold;">var</span> memoizedFunc1 <span style="color: #339933;">=</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> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>param1<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">return</span> param1 <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>param1<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span>cache<span style="color: #009900;">&#91;</span>param1<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>param1<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is similar, but we use a native Javascript object to cache function results.  As long as the parameter, <code>param1</code>, is primitive<a href="#update_2 ">*</a> (or is serializable to a unique string), this will work great.  Property names must be serialized to strings.  Objects that do not have a <code>toString()</code> method to generate a unique string will generally not work.  In most situations, though, you&#8217;ll have an id or key that you can use, anyway.</p>
<p>The inner function simply checks if it already has a value cached and returns it.  Otherwise, it generates a value, caches it, and returns it.</p>
<p><strong>Success! </strong> A memoized function that does not pollute the function instance (and doesn&#8217;t use global variables like some other implementations I&#8217;ve seen).</p>
<h2>A more interesting case: two parameters</h2>
<p>But let&#8217;s not stop there.  What if we have two parameters?  I guess we could generate some sort of string key out of the parameters and use the single-parameter memoized function.  But why?  Generating a unique hash code is expensive and bulky.  Let&#8217;s try to build a 2-parameter memoized function without that.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// multi-valued function with two params</span>
<span style="color: #006600; font-style: italic;">// this time we use two levels of closures and two cache objects</span>
<span style="color: #003366; font-weight: bold;">var</span> memoizedFunc2 <span style="color: #339933;">=</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> cache1 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>param1<span style="color: #339933;">,</span> param2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>param1 <span style="color: #000066; font-weight: bold;">in</span> cache1<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                cache1<span style="color: #009900;">&#91;</span>param1<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</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> cache2 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
                    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>param2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                        <span style="color: #000066; font-weight: bold;">return</span> param2 <span style="color: #000066; font-weight: bold;">in</span> cache2 <span style="color: #339933;">?</span> cache2<span style="color: #009900;">&#91;</span>param2<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span>cache2<span style="color: #009900;">&#91;</span>param2<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>param1<span style="color: #339933;">,</span> param2<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</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: #000066; font-weight: bold;">return</span> cache1<span style="color: #009900;">&#91;</span>param1<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span>param2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Heh.  The solution is to build two levels of closures!  The first level creates and caches the second level as needed!  The first-level cache ends up holding a reference to an inner anonymous function for each unique <code>param2</code> (and each inner function has it&#8217;s own unique closure).</p>
<h2 id="gen_sol">A general purpose &#8220;memoizer&#8221;</h2>
<p>The two-parameter case is quite ugly and unwieldy, in my opinion.  However, it shed some light on a general-purpose solution, a &#8220;memoizer&#8221; I&#8217;d like to call it.  With a little bit of work, I was able to devise a memoizer for any function with explicitly-declared parameters.  Here it is:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// memoize: a general-purpose function to enable a function to use memoization</span>
<span style="color: #006600; font-style: italic;">//   func: the function to be memoized</span>
<span style="color: #006600; font-style: italic;">//   context: the context for the memoized function to execute within</span>
<span style="color: #006600; font-style: italic;">//   Note: the function must use explicit, primitive parameters (or objects</span>
<span style="color: #006600; font-style: italic;">//     that generate unique strings in a toString() method)</span>
<span style="color: #003366; font-weight: bold;">function</span> memoize <span style="color: #009900;">&#40;</span>func<span style="color: #339933;">,</span> context<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> memoizeArg <span style="color: #009900;">&#40;</span>argPos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> cache <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</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: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span> <span style="color: #000066; font-weight: bold;">in</span> cache<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    cache<span style="color: #009900;">&#91;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> func.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>context<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">return</span> cache<span style="color: #009900;">&#91;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span> <span style="color: #000066; font-weight: bold;">in</span> cache<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    cache<span style="color: #009900;">&#91;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> memoizeArg<span style="color: #009900;">&#40;</span>argPos <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">return</span> cache<span style="color: #009900;">&#91;</span>arguments<span style="color: #009900;">&#91;</span>argPos<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #006600; font-style: italic;">// JScript doesn't grok the arity property, but uses length instead</span>
    <span style="color: #003366; font-weight: bold;">var</span> arity <span style="color: #339933;">=</span> func.<span style="color: #660066;">arity</span> <span style="color: #339933;">||</span> func.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> memoizeArg<span style="color: #009900;">&#40;</span>arity <span style="color: #339933;">-</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This still might look a little crazy, but it&#8217;s really quite simple.  To satisfy an infinite number of parameters, we simply use recursion.  Every time we recurse, we create another closure.  This just happens in Javascript.  It&#8217;s a natural side-effect of recursion in the language.  All we have to do is use the closures to cache our results.</p>
<p>Our <code>memoize</code> function takes two arguments.  The first is a reference to the function we want to memoize.  The second is the context the memoized function should run in.  For instance, if we want to memoize an object method, we would pass the method in as the first parameter and the object itself as the second parameter.</p>
<p>When the <code>memoize</code> function executes, it first discerns how many formal (explicit) parameters the function has.  Javascript uses the <code>arity</code> property for this purpose.  Of course, no interesting Javascript project would be complete without a Microsoft caveat of some sort.  For some idiotic reason, JScript uses the <code>length</code> property instead of <code>arity</code>.  Other Javascript engines followed suit and deprecated the <code>arity</code> property in favor of the <code>length</code> property.</p>
<p>Next, <code>memoize</code> calls its inner function <code>memoizer</code> on the last parameter.  <code>memoizer</code> constructs a local cache and returns an inner function that either executes and caches our original function if we&#8217;re at the first parameter — or else it caches and executes a call to <code>memoizer</code> with the previous parameter <code>(argPos - 1)</code>.  Each time the function, <code>memoizer</code>, is recursively called it creates a closure around its own <code>cache</code> variable.</p>
<p>Notice that we&#8217;re using the <code>apply</code> method when we finally call our original function.  This allows us to bind to our original context.  We&#8217;re also using <code>apply</code> when we recursively call <code>memoizer</code>.  This allows us to pass the arguments through without knowing how many arguments there are.  The <code>this</code> passed into these calls is arbitrary and could easily have been anything else, including <code>null</code>.</p>
<p>I don&#8217;t know why I chose to start at the last parameter and go backwards.  This routine could go in either direction.  I also have no idea whether this memoizer is any faster or leaner than Stoyan&#8217;s.  I imagine it doesn&#8217;t matter when you consider that both should be much, much faster than the lengthy XHR call or computationally intensive calculation they are meant to prevent.</p>
<h2>OK.  Cool.  But &#8230; um &#8230; why?</h2>
<p>Yes, memoization is a neat concept.  But why use it rather than just hand-coded caching mechanisms?  It&#8217;s easy enough to write a caching routine, right?  Here are a few good reasons:</p>
<ul>
<li>hand-coded caching mechanisms obfuscate your code</li>
<li>multi-variate caching routines are bulky in Javascript</li>
<li>fewer lines of code means fewer bugs</li>
<li>Java programmers will think more highly of you*</li>
</ul>
<p>*Javascript kicks a$$.  Show those stodgy back-end guys what we&#8217;re capable of!</p>
<h2>Let&#8217;s try it out</h2>
<p>So, let&#8217;s test it.  First, let&#8217;s create a sample object to work with.  This object has an &#8220;expensive&#8221; method that uses an XHR request to fetch server-side resources.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// myObj constructor</span>
<span style="color: #003366; font-weight: bold;">function</span> myObj <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
myObj.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    expensiveAjaxLookup<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>y<span style="color: #339933;">,</span> mo<span style="color: #339933;">,</span> d<span style="color: #339933;">,</span> h<span style="color: #339933;">,</span> mn<span style="color: #339933;">,</span> s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// OK.  No XHR.  Just pretend it does something on the server!</span>
        <span style="color: #006600; font-style: italic;">// Instead we're just going to construct a date string.  Lame, I know.</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">prop</span> <span style="color: #339933;">+</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span>y <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> mo <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> d <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> h <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> mn <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> s <span style="color: #339933;">||</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// a public property to prove that &quot;this&quot; is really &quot;this&quot; in our memoized methods</span>
    prop<span style="color: #339933;">:</span> <span style="color: #3366CC;">'my date: '</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In order to prove that our memoized methods didn&#8217;t mangle the context of the original method, I added a public property and used it in the <code>expensiveAjaxLookup</code> method.  If our memoized methods lost their context, then this property would be undefined.</p>
<p>Tests:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> o <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> myObj<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
o.<span style="color: #660066;">memoizedLookup</span> <span style="color: #339933;">=</span> memoize<span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">expensiveAjaxLookup</span><span style="color: #339933;">,</span> o<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">// Note: 8 == September, not August in Javascript</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">16</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">9</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">16</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">16</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">21</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">13</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">26</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>o.<span style="color: #660066;">memoizedLookup</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">21</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">13</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">26</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Output:</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">my date: Thu Sep 17 2009 00:00:00 GMT-0400 (EDT)
my date: Wed Sep 16 2009 00:00:00 GMT-0400 (EDT)
my date: Fri Oct 16 2009 00:00:00 GMT-0400 (EDT)
***** cache hit!
my date: Wed Sep 16 2009 00:00:00 GMT-0400 (EDT)
my date: Mon Sep 21 2009 13:26:17 GMT-0400 (EDT)
***** cache hit!
my date: Mon Sep 21 2009 13:26:17 GMT-0400 (EDT)</pre></div></div>

<p>As you can see, the context was correctly bound.  Otherwise, we&#8217;d see &#8221; <code>undefinedThu Sep 17 2009 00:00:00 GMT-0400 (EDT)</code>&#8220;.  The lines that say &#8220;<code>***** cache hit!</code>&#8221; are some debugging statements I threw in.  I sprinkled some console.log() calls all over the memoize function to ensure that the caches were being used as expected.  They are, of course.  I&#8217;ll leave it as an exercise for you to study the behavior of the function, if you are so inclined.  I found the output very interesting and revealing.  Go ahead.  Have fun with it!</p>
<p><strong><em>So, what uses can you conceive for memoization in web apps?  Is it only good for caching XHR requests or summing Fibonacci series?  Please leave a comment or let me know on Twitter!</em></strong></p>
<hr /><strong>[Update]</strong> I just came across two interesting Javascript memoization articles.  In one, the author included an &#8220;unmemoize&#8221; function.  In the other, the &#8220;unmemoification&#8221; happened automatically at a specified time delay.  In the first implementation, though, the function instances are used to hold the unmemoize method.  In the second, a hash key is generated to handle multiple parameters.</p>
<p>It&#8217;s certainly possible to add both features without either of those sacrifices.  I have some ideas how it could be done.  <strong><em>Do you have an implementation that works?  If so, please leave a comment!</em></strong></p>
<p><a href="http://talideon.com/weblog/2005/07/javascript-memoization.cfm">Memoization in JavaScript</a></p>
<p><a href="http://blog.stevenlevithan.com/archives/timed-memoization">Timed Memoization</a></p>
<p>In this article, memoization is used to speed up Bezier curve calculations: <a href="http://osteele.com/archives/2006/04/javascript-memoization">One-Line JavaScript Memoization</a></p>
<hr /><strong id="update_2">[Update 2]</strong>I updated the post to remove references to the word &#8220;serializable&#8221; since I really meant primitives.  In Javascript, all objects are serializable.  However, I really meant <em>uniquely serializable</em>.  All primitives in Javascript are uniquely serializable (<code>String(37)</code> will always be &#8220;37&#8243;).  Objects, Functions, and Arrays are not always unique when serialized.  In most engines, objects, for instance, serialize as &#8220;[Object object]&#8220;.  Dates, despite not being primitive, do have unique serializations (but are locale-dependent).</p>
<p>I also updated the text to clarify that the <code>arity</code> property has been deprecated in favor of the <code>length</code> property.  </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/05/01/a-better-javascript-memoizer/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Hi-performance Javascript Tips #3: Less is More [Updated 2009-04-09]</title>
		<link>http://unscriptable.com/2009/04/09/hi-performance-javascript-tips-3-less-is-more/</link>
		<comments>http://unscriptable.com/2009/04/09/hi-performance-javascript-tips-3-less-is-more/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 07:02:52 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[dojo]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=250</guid>
		<description><![CDATA[Sure, Javascript engines have matured. Safari's Nitro, Chrome's V8, Firefox's TraceMonkey, and Opera's Carackan all kick some serious butt.  (IE8's JScript, unfortunately, still sucks wind.)  However, routines written in C++ still run orders of magnitude faster in most cases.  ]]></description>
			<content:encoded><![CDATA[<p>This should really be Tip #1 since it&#8217;s the most critical of all.  Let me just say this as clearly as possible:</p>
<p><em><strong>Your fastest Javascript projects are the ones that have the least Javascript!</strong></em></p>
<p>Sure, Javascript engines have matured. Safari&#8217;s Nitro, Chrome&#8217;s V8, Firefox&#8217;s TraceMonkey, and Opera&#8217;s Carackan all kick some serious butt.  (IE8&#8242;s JScript, unfortunately, still sucks wind.)  However, routines written in C++ still run orders of magnitude faster in most cases.  </p>
<p><em>Don&#8217;t write Javascript to do something your browser already does at compiled-code speeds.</em><br />
<span id="more-250"></span><br />
Do you have any idea now many person-years of effort went into the regular expressions engine in your browser?  Tap into that resource!  </p>
<p>Here are some other resources you may be under-utilizing:</p>
<ul>
<li>Array.prototype.join <a href="http://unscriptable.com/index.php/2009/03/19/hi-performance-javascript-tip-2-revisited/">(example)</a></li>
<li>Array.prototype.slice <a href="http://unscriptable.com/index.php/2009/03/19/hi-performance-javascript-tips-1/">(example)</a></li>
<li>RegExp (many string-related optimizations!)</li>
<li><a href="https://developer.mozilla.org/En/New_in_JavaScript_1.6#Array_extras">Array iterators</a></li>
<li>DOM selectors (such as Acme (dojo) and Sizzle)</li>
</ul>
<p>I&#8217;ll dive into each of these in later blog posts, but here&#8217;s a teaser.  This example shows how to replace a relatively slow <code>while</code> loop with an Array iterator.</p>
<p>Our while loop:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> nodes <span style="color: #339933;">=</span> dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'*[title]'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #006600; font-style: italic;">// using dojo just as an example</span>
    found<span style="color: #339933;">,</span> <span style="color: #006600; font-style: italic;">// we're looking for a particular node and will store it here</span>
    len <span style="color: #339933;">=</span> nodes.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> <span style="color: #006600; font-style: italic;">// performance boost to grab this outside of the loop</span>
    i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// just an iteration counter</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>found <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// found will remain false until we find our node</span>
    found <span style="color: #339933;">=</span> nodes<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'title'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Loading'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">0</span> <span style="color: #339933;">&amp;&amp;</span> nodes<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    i<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>found<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// do something with &lt;&lt;found&gt;&gt; here</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>That&#8217;s not a bad while loop.  You&#8217;ll notice that I am overloading the meaning of the <code>found</code> variable.  <em>This is an acceptable practice in high-performance situations as long as the code is well-documented to prevent confusion.</em></p>
<p>Here&#8217;s the same loop utilizing the Array iterator <code>some</code> wrapped by dojo NodeList&#8217;s <code>some</code> method:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> found<span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// we're looking for a particular node and will store it here</span>
dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'*[title]'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">some</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>node<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// found will remain false until we find our node</span>
    found <span style="color: #339933;">=</span> node.<span style="color: #660066;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'title'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Loading'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">0</span> <span style="color: #339933;">&amp;&amp;</span> node<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> found<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>found<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// do something with &lt;&lt;found&gt;&gt; here</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Leaner!  Faster!  Sexier!</p>
<hr/>
<p>OK.  Here&#8217;s the point where I scratch my head.  I just ran both of these against <a href="http://dojocampus.org/">dojocampus.org</a> in FF 3.1 and Safari 4.0.  To my surprise, the <code>while</code> loop performed slightly better than the <code>some</code> (1ms difference).  I removed the <code>[title]</code> attribute from the query selector to get some better test data.  Same story.</p>
<p>There was a big difference in IE7, though.</p>
<p>I guess the latest Javascript engines really do kick butt!!!!</p>
<hr/>
<strong>Update 2009-04-09:</strong></p>
<p>My best guess is that the NodeList that <code>dojo.query</code> returns is slowing our example code.  A NodeList is not a true array.  It is an Array-like object, which simply means it exposes its list of items as properties whose names are Cardinal number and also exposes a length property.  So I created a quick and dirty test on a true array:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// using some</span>
<span style="color: #003366; font-weight: bold;">var</span> a <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</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> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> a<span style="color: #009900;">&#91;</span>i<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: #CC0000;">2009</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> found<span style="color: #339933;">,</span> s <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: #339933;">;</span>
a.<span style="color: #660066;">some</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: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    found <span style="color: #339933;">=</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">99999</span> <span style="color: #339933;">?</span> <span style="color: #000066; font-weight: bold;">item</span> <span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> found<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</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: #009900;">&#41;</span> <span style="color: #339933;">-</span> s<span style="color: #339933;">,</span> found<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// using while</span>
<span style="color: #003366; font-weight: bold;">var</span> len <span style="color: #339933;">=</span> a.<span style="color: #660066;">length</span><span style="color: #339933;">,</span> found <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">,</span> s <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: #339933;">,</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>found <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   found <span style="color: #339933;">=</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">99999</span> <span style="color: #339933;">?</span> a<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    i<span style="color: #339933;">++;</span>
<span style="color: #009900;">&#125;</span>
console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</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: #009900;">&#41;</span> <span style="color: #339933;">-</span> s<span style="color: #339933;">,</span> found<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The results showed that some ran about 17% faster in Firefox 3.0, 32% faster in Firefox 3.1beta, and 43% faster in Safari 4.0beta.  Of course, the code inside our loop is very simple.  More complex code will consume a larger slice of the total time and will therefore make the effect of the loop mechanism less important.  </p>
<p>Moral of the story: to get the best performance when looping through real arrays (rather than Nodelists or Array-like objects), use the Array iterators or their browser-safe counterparts in the major libraries.  When using NodeLists, either method works great as long as you&#8217;ve tuned your loop correctly.  (Sounds like another blog post&#8230;)</p>
<p>I&#8217;d like to hear from you!  What library do you use and how does it handle Array iterators?</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/04/09/hi-performance-javascript-tips-3-less-is-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hi-performance Javascript Tips #2 «Revisited»</title>
		<link>http://unscriptable.com/2009/03/19/hi-performance-javascript-tip-2-revisited/</link>
		<comments>http://unscriptable.com/2009/03/19/hi-performance-javascript-tip-2-revisited/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 13:58:31 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=157</guid>
		<description><![CDATA[In a previous post, we recreated a simple version of Java's StringBuilder...  I was thinking it would be fun to add a few more features of Java's StringBuilder onto our decidedly simple example.  Here's how we could add a separator property and a length property (with setter and getter):]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://unscriptable.com/index.php/2009/03/19/hi-performance…ascript-tips-2/">previous post</a>, we recreated a simple version of Java&#8217;s StringBuilder:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> StringBuilder <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> _stack <span style="color: #339933;">=</span> str <span style="color: #339933;">?</span> <span style="color: #009900;">&#91;</span>str<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// str == initial string to start, if any</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// append can take one or more strings as arguments</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">append</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>
        _stack.<span style="color: #660066;">push</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>_stack<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">toString</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>separator<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> _stack.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span>separator <span style="color: #339933;">||</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Unlke Java&#8217;s implementation, we&#8217;ve added a separator parameter to the toString() method.  This would be very helpful in creating HTML or CSV using our object.  </p>
<p>I was thinking it would be fun to add a few more features of Java&#8217;s StringBuilder onto our decidedly simple example.  Here&#8217;s how we could add a separator property and a length property (with setter and getter):<br />
<span id="more-157"></span></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> StringBuilder <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> _stack <span style="color: #339933;">=</span> str <span style="color: #339933;">?</span> <span style="color: #009900;">&#91;</span>str<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #006600; font-style: italic;">// str == initial string to start, if any</span>
        _length <span style="color: #339933;">=</span> str.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// length of initial string</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">separator</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">''</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// separator used when concatenating strings in the stack</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// public methods </span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">append</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: #006600; font-style: italic;">// append can take one or more strings as arguments</span>
        _stack.<span style="color: #660066;">push</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>_stack<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        toArray<span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> _length <span style="color: #339933;">+=</span> str.<span style="color: #660066;">length</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</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: #000066; font-weight: bold;">return</span> _length<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">setLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// coalesce what we've already got and cut it to length</span>
        <span style="color: #006600; font-style: italic;">// Note: this does not expand the string. it only clips it.</span>
        _stack <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>_coalesce<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">separator</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> len<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        _length <span style="color: #339933;">=</span> len<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">toString</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>altSeparator<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> _coalesce<span style="color: #009900;">&#40;</span>altSeparator <span style="color: #339933;">==</span> undefined <span style="color: #339933;">?</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">separator</span> <span style="color: #339933;">:</span> altSeparator<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// private methods</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">function</span> _coalesce <span style="color: #009900;">&#40;</span>separator<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// consolidates all of the string entries into one string</span>
        <span style="color: #003366; font-weight: bold;">var</span> str <span style="color: #339933;">=</span> _stack.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span>separator <span style="color: #339933;">||</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        _stack <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>str<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        _length <span style="color: #339933;">=</span> str.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> str<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>See my previous post for the implementation of toArray.  Unfortunately, IE 6 &#038; 7 are pitifully behind the rest of the Javascript world and need additional help.  See the following article from Mozilla for implementing the forEach iterator method in IE:</p>
<p><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/forEach">forEach</a></p>
<p><a href="http://unscriptable.com/index.php/2009/03/19/hi-performance-javascript-tips-1/">toArray</a></p>
<p>There&#8217;s a potentially nasty side-effect in the setLength() method.  If you were planning to use the altSeparator parameter in the toString() method, but you use the setLngth() method first, the separator property will be used instead!  Either we should create excellent documentation; write a somewhat slower, but safe implementation of setLength(); or remove the altSeparator parameter (and possibly the separator property) and move it to the constructor.  </p>
<p>Sample output:</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">var sb = new StringBuilder('fun');
sb.append('stuff', 'with', 'javascript');
sb.separator = ' ';
sb.setLength(10);
'string=&quot;' + sb.toString() + '&quot; length=' + sb.getLength();
&nbsp;
&quot;string=&quot;fun stuff &quot; length=10&quot;</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/03/19/hi-performance-javascript-tip-2-revisited/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hi-performance Javascript Tips #2</title>
		<link>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-2/</link>
		<comments>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-2/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 06:33:12 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/index.php/2009/03/19/hi-performance-javascript-tips-2/</guid>
		<description><![CDATA[Create your own version of Java&#8217;s StringBuilder: var StringBuilder = function &#40;str&#41; &#123; var _stack = str ? &#91;str&#93; : &#91;&#93;; // str == initial string to start, if any &#160; // append can take one or more strings as arguments this.append = function &#40;&#41; &#123; _stack.push.apply&#40;_stack, arguments&#41;; return this; &#125; &#160; this.toString = function [...]]]></description>
			<content:encoded><![CDATA[<p>Create your own version of Java&#8217;s StringBuilder:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> StringBuilder <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> _stack <span style="color: #339933;">=</span> str <span style="color: #339933;">?</span> <span style="color: #009900;">&#91;</span>str<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// str == initial string to start, if any</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// append can take one or more strings as arguments</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">append</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>
        _stack.<span style="color: #660066;">push</span>.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span>_stack<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">toString</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>separator<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> _stack.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span>separator <span style="color: #339933;">||</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This routine runs up to 8x faster in IE6 than normal string concatenation using the + and += operators!  In IE7, I&#8217;ve clocked a 4x improvement.  </p>
<p>Firefox 3.0 gets about a 20% speed boost.  Safari 4 and Chrome get less than a 10% speed boost.</p>
<p>It would be an easy exercise to modify the StringBuilder class&#8217; append method and constructor to take an existing StringBuilder object instead of a string.</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hi-performance Javascript Tips #1 [Updated 2009-03-19]</title>
		<link>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-1/</link>
		<comments>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-1/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 06:12:26 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=108</guid>
		<description><![CDATA[The arguments property of the Function object looks a lot like an array, but it&#8217;s really not. We say it&#8217;s array-like since it has a length property and properties whose names are whole numbers. Similary, DOM properties, such as Element.childNodes, return a NodeList, which is also array-like. If you&#8217;ve ever been frustrated that you can&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>The arguments property of the Function object looks a lot like an array, but it&#8217;s really not.  We say it&#8217;s <em>array-like</em> since it has a length property and properties whose names are whole numbers.</p>
<p>Similary, DOM properties, such as Element.childNodes, return a NodeList, which is also <em>array-like</em>.  </p>
<p>If you&#8217;ve ever been frustrated that you can&#8217;t use array methods on these <em>array-like</em> collections, then the following function is your new friend:<br />
<span id="more-108"></span></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> toArray <span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>obj<span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I like this version because it&#8217;s so compact!  It&#8217;s also very fast since it runs at compiled-code speeds.  Here&#8217;s a version that even faster because it eliminates the construction of the stub array ([]) each time:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>ns<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> _a <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    ns.<span style="color: #660066;">toArray</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
        <span style="color: #000066; font-weight: bold;">return</span> _a.<span style="color: #660066;">slice</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>obj<span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>window<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>I used a closure to hide the stub array and keep the global namespace clean.  Pass-in your own object / namespace (instead of window) to use the toArray function as a method on that object.</p>
<p>Most Javascript libraries have this feature built-in already, but this first example is one of my all-time favorites since it&#8217;s so short!  </p>
<p><strong>[Update: kangax improved my toArray function greatly (see discussion).  Here are the results:]</strong></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> toArray <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>slice<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> toArray <span style="color: #009900;">&#40;</span>object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> slice.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>object<span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>Array.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>I remember the first time I saw something like this.  It made my head ache.  It&#8217;s best to go line by line, starting at the middle:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">return</span> slice.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>object<span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you&#8217;ve understood the post this far, you probably already know that &#8220;call&#8221; is a method of the Function prototype that executes its function in the scope of another object.  Here, we&#8217;re executing slice in the context of our <em>array-like</em> object.  Any remaining parameters to the call method are passed as formal parameters to slice.  Here, calling slice with zero for the first parameter and no second parameter just tells slice to grab all items.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> toArray<span style="color: #009900;">&#40;</span>object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span></pre></div></div>

<p>The line immediately above declares our toArray function as well as the formal parameter for our <em>array-like</em> object.  The return statement indicates that we&#8217;re going to pass our toArray function&#8217;s reference somewhere.  Of course, it&#8217;s going to be assigned to our top-level toArray variable, but first let&#8217;s investigate the first and last lines:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> toArray <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>slice<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   . . .
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>Array.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here, we&#8217;re declaring an anonymous function with one parameter, slice.  Then we&#8217;re <em>executing</em> the function, passing it a reference to Array.prototype.slice.  This is an easy way to <em>declare and assign</em> a local variable to the slice function in our anonymous function.  (The parentheses around the anonymous function cure a syntax ambiguity.)  Since we&#8217;re executing the anonymous function immediately (inline execution), we&#8217;re returning the value from the outer return statement (return function toArray) directly into the outer toArray variable.  </p>
<p>In case you missed it: the outer function executes immediately, returning the inner function (toArray), which will be executed when we call our [inner] toArray function &#8212; the one referenced in the toArray top-level variable!  (If this is your first time doing this <em>crazy s**t</em>, you better re-read that a few times.)</p>
<p>kangax brings up an excellent point.  Debuggers don&#8217;t typically introspect very deeply (and certainly won&#8217;t grok this construct).  Therefore, it is important to name any non-trivial functions (e.g. our inner function) so that the name can be shown in stack traces, etc.  A stack trace full of calls to <code>function ()</code> aren&#8217;t very helpful.  However, it is also important not to name any functions that may pollute our global namespace (e.g. our outer, inline-executed anonymous function).  </p>
<p>OK.  Now that that&#8217;s settled, I will attempt to make our toArray function as small as possible.  In the early 90&#8242;s when I worked with an APL programmer.  He always claimed he could write a whole application in 1 line of code.  It turned into a big joke around the office.  But I guess I took it to heart.  Here&#8217;s my attempt at the smallest, high-performance, non-polluting, general-purpose toArray function:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> toArray <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>o<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> s.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>o<span style="color: #339933;">,</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">slice</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Go ahead.  Beat that.</p>
<p>(Yah.  I know I am breaking so many <em>best practices</em> here, but I just had to try it!)</p>
<h2>OK. So why is this so important?</h2>
<p>So what makes this better than just placing calls to <code>Array.prototype.slice.call(obj, 0)</code> all over your code?  </p>
<p><strong>Reason #1: Clarity.  </strong>The reader doesn&#8217;t get bogged down by implementation details.  </p>
<p><strong>Reason #2: Speed.  </strong>At execution time, there are less lookups by the Javascript interpreter (2 versus 4), but only one extra reference to a local variable (s).  References to local variables are much faster than lookups.  Lookups occur every time you reference a member (every &#8220;.&#8221; in dot notation) and every time you reference a global variable.</p>
<p><strong>Reason #3: Light weight.  </strong>Calling <code>toArray(obj)</code> yields smaller code than using <code>Array.prototype.slice.call(obj, 0)</code>.  It only takes 4 calls to toArray before your code starts getting smaller.</p>
<p><strong>Reason #4: Understandable.  </strong>You won&#8217;t perturb the <a href="http://unscriptable.com/index.php/2009/03/19/javascript-for-java-stoics-a-twitter-series/">Java Stoics</a> who have to understand your code. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2009/03/19/hi-performance-javascript-tips-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

