<?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"
	>

<channel>
	<title>The Fluid Project Blog</title>
	<atom:link href="http://fluidproject.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://fluidproject.org/blog</link>
	<description></description>
	<pubDate>Wed, 27 May 2009 14:25:37 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<item>
		<title>Infusion 1.0 Has Been Released!</title>
		<link>http://fluidproject.org/blog/2009/05/26/infusion-10-has-been-released/</link>
		<comments>http://fluidproject.org/blog/2009/05/26/infusion-10-has-been-released/#comments</comments>
		<pubDate>Wed, 27 May 2009 01:39:17 +0000</pubDate>
		<dc:creator>colin</dc:creator>
		
		<category><![CDATA[Community]]></category>

		<category><![CDATA[Project coordination]]></category>

		<category><![CDATA[Site News]]></category>

		<category><![CDATA[The Fluid Community]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/?p=69</guid>
		<description><![CDATA[World, Meet Infusion 1.0
The Fluid community shipped Infusion 1.0 a couple of weeks ago. Before making a splash with announcements about the release, we wanted to take some time to revisit our documentation and sample code to be sure they are really useful and comprehensive. Recognizing that it&#8217;s not enough just to ship a bundle [...]]]></description>
			<content:encoded><![CDATA[<h3>World, Meet Infusion 1.0</h3>
<p>The Fluid community shipped <a href="http://fluidproject.org/products/infusion/">Infusion 1.0</a> a couple of weeks ago. Before making a splash with announcements about the release, we wanted to take some time to revisit our documentation and sample code to be sure they are really useful and comprehensive. Recognizing that it&#8217;s not enough just to ship a bundle of code, we try to provide a <a href="http://wiki.fluidproject.org/display/fluid/Infusion+Documentation">whole package of resources</a> for developers and designers who are using Infusion. That means comprehensive API pages, tutorials to get you started, and concepts documentation to give you insights into the philosophy and design patterns we&#8217;ve built into Infusion. With this new documentation in place, now&#8217;s the time to share the news of Infusion 1.0&#8217;s release more widely.</p>
<p>Fluid Infusion is an <a href="http://wiki.fluidproject.org/display/fluid/Infusion+Framework">application framework</a> for building usable and accessible user interfaces with JavaScript. Built on top of <a href="http://jquery.com">jQuery</a>, Infusion takes a different approach to client-side development. At heart, Infusion is an open architecture designed to put you back in control of your application&#8217;s user experience. It includes a <a href="http://wiki.fluidproject.org/display/fluid/Components">growing collection of UI components</a>—reusable interactions that go deeper than most widgets.  Created by a community of developers and interaction designers, Infusion components are built from the ground up with accessibility in mind. All of our designs can be used with assistive technologies, are fully controllable with the keyboard, and can be transformed to suit your users&#8217; personal needs.</p>
<p>Knowing that you can&#8217;t bottle good design, our components can be easily adapted and reworked to suit your creativity. We give you the ability to tweak more than just a few stylesheets—you can totally change the markup of a component, change its behaviour, or toss your own workflow and logic into the mix.</p>
<h3>What&#8217;s an Application Framework?</h3>
<p>Most JavaScript libraries fit into two categories: foundation toolkits and application frameworks. Foundation toolkits are probably the most familiar, providing all the basic tools required to manipulate the DOM, manage events, and make Ajax calls in a reliable, cross-browser way. <a href="http://jquery.com">jQuery</a> and <a href="http://www.prototypejs.org/">Prototype</a> are probably the best-known examples. Application frameworks, on the other hand, have emerged more recently. With more complex interactions and more application logic moving from the server to the client, there is a need for tools to help manage growing code bases. Application frameworks such as <a href="http://www.sproutcore.com/">Sproutcore</a> and <a href="http://www.dojotoolkit.org/">Dojo + Dojox</a> often provide features such as data binding, support for the <a href="http://c2.com/cgi/wiki?ModelViewController">Model-View-Controller</a> pattern, and HTML template rendering.</p>
<p>Infusion puts a unique spin on things: it takes a <a href="http://wiki.fluidproject.org/display/fluid/Declarative+Configuration">declarative</a> and <a href="http://wiki.fluidproject.org/display/fluid/Infusion+Event+System">event-driven</a> approach, promoting less code and greater flexibility. Built on top of jQuery, everything about Infusion is open: its architecture, source code, and community. Our approach to Model-View-Controller is different, too. <a href="http://wiki.fluidproject.org/display/fluid/Model+Objects">Models</a> and <a href="http://wiki.fluidproject.org/display/fluid/Component+Lifecycle">views</a> are at the heart of Infusion, while controller code is conspicuously absent. Unlike most MVC web frameworks, we think it&#8217;s the job of the framework to take care of the glue, leaving you to focus on the stuff that makes your application tick.</p>
<p>Infusion&#8217;s client-side <a href="http://wiki.fluidproject.org/display/fluid/Renderer">template renderer</a> is completely unobtrusive, allowing you to dynamically render your user interface without having to mix up bits of code with your HTML. No code in your templates means more reuse, less chance for mistakes, and an easier job when it comes time to do a redesign. We also include a <a href="http://wiki.fluidproject.org/display/fluid/Fluid+Skinning+System+(FSS)">lightweight CSS framework</a> that lets you mix and match styles to create beautiful and themeable user interfaces, providing pre-baked layouts, widgets and text styles to get you started. We even give you plugins and framework APIs to help ease the burden of creating user interfaces with JavaScript that will be accessible to a wide range of users.</p>
<p>Interoperability is huge for Infusion. We play nice with other JavaScript code, avoiding the conflicts that are common when combining different JavaScript libraries. This makes Infusion particularly well suited to building mashups, portals, and content management systems.</p>
<h3>Fluid and jQuery</h3>
<p>We love jQuery. Infusion wouldn&#8217;t have been possible without the simplicity and clarity of jQuery&#8217;s approach. We also didn&#8217;t want to reinvent the wheel, so jQuery is everywhere in Infusion. Recognizing that some applications need more, we created Infusion to complement jQuery and other JavaScript libraries. It&#8217;s not an either/or situation—Infusion is very modular, so you can pick and choose the features you need based on the complexity of your project. Go ahead and combine ordinary jQuery code with Infusion, or use the whole framework whenever you need robust data binding, unobtrusive markup generation, and MVC-style designs.</p>
<p>Fluid&#8217;s culture of collaboration and interoperability run deep. To that end, we are active contributors to jQuery UI, <a href="http://www.marcozehe.de/2009/03/07/jquery-ui-17-released/">sharing our accessibility experience and code</a> to help make jQuery even better. Every time we come up with a new accessibility improvement, we share it back with jQuery so that the whole community can benefit.</p>
<h3>What&#8217;s Next?</h3>
<p>This is just the beginning. With Infusion 1.0 out the door, we&#8217;ve got lots of new features and improvements on deck. Indeed, the past few weeks have been packed with tweaks, bug fixes, and  features <a href="http://wiki.fluidproject.org/display/fluid/Fluid+1.1+Release+Status">destined for the Infusion 1.1 release</a>. We&#8217;re planning to ship this next release in early June. Beyond that, we&#8217;ll continue to grow our components and add new features to the framework.</p>
<p>We&#8217;re also active users of Infusion, building applications and helping other open source communities with their user interfaces. To this end, the Fluid community is embarking on a new project called <a href="http://www.fluidproject.org/projects/fluid-engage/">Fluid Engage</a>, in collaboration with <a href="http://fluidproject.org/partners/fluid-engage-partners/">museums and art galleries</a>. We&#8217;ll be working alongside curators, education departments, and exhibit designers to help create mobile-friendly open Web solutions that bring a new level of interactivity and visitor engagement to the museum. Infusion will be the backbone of this effort, and Engage will undoubtedly drive new components and framework features back into Infusion. Keep an eye out for things like new mobile themes for the Fluid Skinning System, designed to provide a natural user experience and to repurpose content for mobile devices like the iPhone. We&#8217;ll also be shipping a new visualization library for Infusion, providing Canvas-based solutions for drawing rich, vector-based images and animations. If any of these features interests you, don&#8217;t hesitate to <a href="http://fluidproject.org/getinvolved/">drop us a line</a> if you&#8217;d like to lend a hand.</p>
<h3>Give it a Spin and Let Us Know</h3>
<p>We&#8217;re really excited to share Infusion with everyone. With the 1.0 release, Infusion offers a stable and reliable solution for building rich user experiences, supported by a dedicated and friendly community. We&#8217;ve got a healthy roadmap moving forward, and a growing community of users. With accessibility and usability baked in from the start, we&#8217;ve got you covered. <a href="http://fluidproject.org/products/infusion/">Download the release</a>, <a href="http://wiki.fluidproject.org/display/fluid/Infusion+Documentation">check out the documentation</a>, dive in, and <a href="http://fluidproject.org/getinvolved/">let us know what you think</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2009/05/26/infusion-10-has-been-released/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A bridge between this and that</title>
		<link>http://fluidproject.org/blog/2008/12/12/a-bridge-between-this-and-that/</link>
		<comments>http://fluidproject.org/blog/2008/12/12/a-bridge-between-this-and-that/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 17:13:27 +0000</pubDate>
		<dc:creator>antranig</dc:creator>
		
		<category><![CDATA[Community]]></category>

		<category><![CDATA[Development]]></category>

		<category><![CDATA[Technology]]></category>

		<category><![CDATA[javascript jquery ui that this durable]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/?p=62</guid>
		<description><![CDATA[In preparing for the final release of Fluid Infusion 0.6 (as of writing, we are at &#8220;Bug Parade&#8221; stage, leading to code freeze for Monday), we found ourselves with the disagreeable requirement to make some incompatible API changes to a part of the framework. Not only why we had to do this, but what we [...]]]></description>
			<content:encoded><![CDATA[<p>In preparing for the final release of Fluid Infusion 0.6 (as of writing, we are at &#8220;Bug Parade&#8221; stage, leading to code freeze for Monday), we found ourselves with the disagreeable requirement to make some incompatible API changes to a part of the framework. Not only why we had to do this, but what we did about it, are interesting.</p>
<p>The code in question was kept in the file <a href="https://source.fluidproject.org/svn/fluid/components/trunk/src/webapp/fluid-components/js/jquery/jquery.keyboard-a11y.js">jquery-keyboard-a11y.js</a>, and has historically always had a &#8220;special status&#8221;. This holds the parts of our framework which we have always considered closest to being contributed to the wider jQuery community (who we are always eager to develop productive relationships with), as a plugin. This code is treated specially, in that special care is made to keep it as self-contained as possible, and in particular to keep it free of dependence on our standard framework base file <a href="https://source.fluidproject.org/svn/fluid/components/trunk/src/webapp/fluid-components/js/fluid/Fluid.js">Fluid.js</a>, to ease its adoption outside our community.</p>
<p>Unfortunately, as of release 1.5, the jQuery UI project included a file ui.selectabe.js, which registers a plugin named &#8220;selectable&#8221; with the same name as one in our set. This is interesting, since it highlights what has been considered a weakness in the jQuery plugin model - that it does not support any infrastructure for namespacing, to ensure that loosely cooperating teams can continue to work in parallel without fear of treading on each other&#8217;s names. This partly reflects its origins - the jQuery &#8220;chained filter&#8221; idiom is admirably matched for expressing queries and primitive operations on the DOM, and has produced a revolutionary condensation in the amount of code necessary to perform these &#8220;bread and butter&#8221; tasks. The plugin model is less well suited to an idiom of <em>construction</em> - that is, when one is using the DOM as a &#8220;springboard&#8221; for the construction of some more complex &#8220;component&#8221; or tree of objects that is going to spend some durable lifetime managing it. This can be seen from the oddity of some code which constructs say a dialog, or a sortable - where *is* the dialog in the following call?</p>
<pre> $("#dialog-root").dialog({bgiframe: true});</pre>
<p>Any &#8220;object&#8221; actually referring to the dialog is implicit - the jQuery standard, is that operations on a jQuery object return another jQuery object (barring the exceptions that they are queries for primitive values such as attributes or counts) - therefore, to interact with this &#8220;dialog&#8221; we must continue to use same-named plugin calls targetted at the same DOM node (another interesting oddity is that the constructed object is not tied to the lifetime of the invoking jQuery object, but to the durability of the DOM nodes addressed by it - this is by necessity, since jQuery objects have no durability).</p>
<p>As a quick aside to those who have not been following these chain of blogs avidly, the Fluid framework design recommendation, since before the 0.5 release, was for &#8220;<a href="http://wiki.fluidproject.org/display/fluid/How+to+Define+a+Unit">that-ism</a>&#8220;, a code structuring device originally recommended by Douglas Crockford. I made an earlier <a href="http://fluidproject.org/blog/2008/07/21/about-this-and-that/">blog posting</a> explaining our decision, and there is also a wiki page on <a href="http://wiki.fluidproject.org/display/fluid/How+to+Define+a+Unit">How to define a Unit</a>. In brief, the benefits of that-ism include greater reliability and predictability of code - in the months since our decision we have been very happy with it, with many contributors commenting that it has made our codebase easier to understand by reading. That-ism also interacts nicely with Javascript&#8217;s natural &#8220;detached function&#8221; idiom - for example it is very easy to write a line such as</p>
<pre>        that.viewEl.click(that.edit);</pre>
<p>without having to worry about awkward &#8220;this&#8221; re-dispatching through event cycles etc - the <code>edit</code> method has natural access to its own, user-defined, and limited, context, without the need for &#8220;this juggling&#8221;. The durability of the returned <code>that</code> from a constructor is also matched to the created object - since it <i>is</i> the created object.</p>
<p>In any case - the jQuery model is marvellous for encoding primitive DOM operations drawn from a fixed set, slightly odd for construction, but poor for namespacing - having lost our namespace for <code>selectable</code> our only option is to move out of the path of the elephant. However, there is no procedure how we can guarantee that further of our names will not collide in the future, so now is an excellent opportunity to think of a scheme to make sure that our users will never again suffer this kind of API incompatibility.</p>
<p>Also, over the lifetime of Fluid, jQuery have firmed up their recommendations and published the following page of <a href="http://docs.jquery.com/UI/Guidelines">Guidelines</a> for plugins - which we could do better at meeting. In particular, they recommend that each thing designated a &#8220;plugin&#8221; use exactly one name in the plugin namespace, in an attempt to head off the namespacing issues I&#8217;ve mentioned.</p>
<p>So, this problem is an excellent opportunity. Can we, at the same time, improve our conformance with jQuery code idioms, solve our namespacing issues permanently, and at the same time improve <code>jquery-keyboard-a11y.js</code> in its agreement with the <code>that</code>-ism enjoyed by the rest of the Fluid codebase?</p>
<p>It sounds impossible, but actually we can. After a lengthy brainstorming session, during which we proved that a &#8220;natural&#8221; namespacing idiom (that is, one which allows function names to be written out as Javascript symbols, rather than as string) is impossible to apply together with a &#8220;this-ist&#8221; dispatching model, we came up with the concept of the &#8220;that-ist bridge&#8221;. This is a small 20-line &#8220;machine&#8221; which now currently sits at the top of <code>jquery-keyboard-a11y.js</code>, and does the work of &#8220;exposing&#8221;, not only the contents of that file, but in fact the entire Fluid framework (where it has potentially conformant arguments) as a single, gigantic jQuery UI plugin named <code>fluid</code>, with exactly the recommended jQuery UI argument semantics.</p>
<p>Here is an example of our old syntax, showing invocation as a jQuery UI plugin named selectable:</p>
<pre>$(".my-nodes").selectable({direction: $.a11y.orientation.HORIZONTAL});</pre>
<p>&#8220;On the ground&#8221;, this has now been rewritten to a that-ist, Fluid-standard construction, used as follows:</p>
<pre>fluid.selectable(".my-nodes", {direction: $.a11y.orientation.HORIZONTAL});</pre>
<p>This is now housed in the global fluid namespace owned by us, permanently heading off the potential for collisions in the future. However, owing to the miracle of the &#8220;that-ist bridge&#8221; machine, this function is now also accessible, for free, using the jQuery UI plugin syntax as follows:</p>
<pre>$(".my-nodes").fluid("selectable", {direction: $.a11y.orientation.HORIZONTAL});</pre>
<p>Essentially any function, which accepts a &#8220;jQueryable&#8221; as its first argument (that is, anything which can legally construct a jQuery object when used as an argument to $, that is, selector strings, DOM nodes, or jQuery objects themselves) will be automatically adapted by the &#8220;that-ist Bridge&#8221; to be invocable using the single, global, Fluid jQuery UI plugin. The arguments are permuted - the first argument to the function becomes the jQuery object itself which the plugin is invoked on, and the symbol for the name of the function becomes a string, the first argument passed to the plugin. The remaining arguments to the function may be passed in an array as the 2nd plugin argument, or if there is a single argument it can be sent directly.</p>
<p>The treatment of return values is also somewhat interesting. The jQuery standard is that jQuery operations return further jQueries - except where they don&#8217;t. It seems that the general exceptions are those which return primitives - so this rule has been formalised in the bridge code. The return value of the underlying Fluid function is examined for its type. If it is a primitive, or &#8220;falsy&#8221; value, it is return directly. If it is some other kind of value, it is assumed that it is some kind of &#8220;Fluidic that&#8221;, and the value is hidden - instead, the original jQuery <code>this</code> is returned, to allow the standard jQuery selector chaining idiom to work. However, as a courtesy, the <em>specific</em> jQuery object returned is decorated with an extra method <code>that()</code> by which the originally returned value can be retrieved.</p>
<p>This has been a big win all round - since at the same time we have been able to improve conformance both with our own coding standards, as well as jQuery&#8217;s. And further, we have now been able to extend to the contents of this file the protection of our version management strategy, first brought in in Fluid 0.5 - by means of a namespacing trick, multiple versions of the Fluid framework may be included into the same document, whilst at the same time not only not colliding in namespace, but even remaining simultaneously addressible from the same scope by specially aware code. Truly necessity is the mother of invention. Or else, a loaf of bread.</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/12/12/a-bridge-between-this-and-that/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Finding things quickly</title>
		<link>http://fluidproject.org/blog/2008/08/14/finding-things-quickly/</link>
		<comments>http://fluidproject.org/blog/2008/08/14/finding-things-quickly/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 17:17:12 +0000</pubDate>
		<dc:creator>antranig</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Technology]]></category>

		<category><![CDATA[cache]]></category>

		<category><![CDATA[data]]></category>

		<category><![CDATA[dom]]></category>

		<category><![CDATA[javascript]]></category>

		<category><![CDATA[jquery]]></category>

		<category><![CDATA[lookup]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/?p=54</guid>
		<description><![CDATA[There are many ways of finding things in the DOM - sometimes, many ways of evaluating apparently the same expression. For example, CSS and JQuery allow you to find elements by id, using an expression of the form
  var myElement=$("#my-element-id");
as well as the apparently equivalent expression
  var myElement=$("[id=my-element-id]");
However, these expressions are different in [...]]]></description>
			<content:encoded><![CDATA[<p>There are many ways of finding things in the DOM - sometimes, many ways of evaluating apparently the same expression. For example, CSS and JQuery allow you to find elements by id, using an expression of the form</p>
<pre>  var myElement=$("#my-element-id");</pre>
<p>as well as the apparently equivalent expression</p>
<pre>  var myElement=$("[id=my-element-id]");</pre>
<p>However, these expressions are different in many ways. One advantage of the latter is that it is more resistant to escaping issues - for example, the colon character <code>:</code> is actually a valid part of an XML id, but is not correctly handled in many escaping situations. JQuery will not accept it as part of a <code>#</code> expression, but is fine in an <code>id</code> specification. This was the basis of our adoption of the latter for the <code>fluid.jById</code> utility.</p>
<p>However, these types of selectors are treated very differently within the nuts-and-bolds of the jQuery selector engine. <code>#</code> selectors have a very special status, which enables numerous shortcuts including the judicious use of <code>document.getElementById</code> where possible. <code>id</code> selectors are just standard attribute value filters, and will perform a full scan of the DOM.</p>
<p><!--<br />
.my-header * {<br />
font-size: 1em;<br />
font-family: courier;<br />
}<br />
--></p>
<table border="0">
<tbody>
<tr>
<td><code>document.getElementById("my-id")</code></td>
<td>8.5µs</td>
</tr>
<tr>
<td><code>$(document.getElementById("my-id"))</code></td>
<td>24µs</td>
</tr>
<tr>
<td><code>$("[id=my-id]&#8220;) </code></td>
<td>12<strong>ms</strong></td>
</tr>
</tbody>
</table>
<p>These tests were done on Firefox 2 in a rather busy document of about 40K of HTML.</p>
<p>Note that the cost of simply wrapping a DOM element in a jQuery object is small, but still noticeable.</p>
<h4>Cost of guarding</h4>
<p>This immediately suggests a policy of falling back on <code>document.getElementById</code> for quick lookups - however, jQuery, being a mature framework, is doing some work for us here in insulating us from an awkward IE bug where <code>document.getElementById</code> is sometimes returning an element which has a match on *name* rather than a match on *id*. This is a rather awkward tradeoff - putting in a &#8220;guard branch&#8221; to check that the required id is actually present as an attribute slows down access for everyone to 22µs, with the option to default back to the jQuery scan. However, do we really want a library with the contract &#8220;give me the element with this id, unless there is something screwy about your document, in which case give me the element 1000 times slower&#8221;. Probably the user will not thank you in this case, and would prefer to be given the chance to fix their markup.</p>
<h4>Quick access to DOM nodes</h4>
<p>This brings us back to why any of these issues are particularly interesting in the first place. I am currently working on reforming the Fluid Reorderer component, not only from a structural but also a performance point of view. The behaviour of the jQuery droppable library is not quite what we would want, both from a performance as well as a behavioural point of view (might be the subject of a separate blog posting), but in fixing it we are faced with some crucial design decisions about how to arrange data structures such that they can be used for very quick access - ordinarily this is not so important, but a DnD library is going to be queried on every mouse move event, and so even timings in microseconds can begin to mount up.</p>
<p>There are two main options -</p>
<p>i) store a &#8220;reverse lookup&#8221; cache of jQuery.data id numbers onto DOM nodes, and work with data structures storing jQuery.data ids, or<br />
ii) synthesise short unique ids onto DOM nodes that do not have them, and work with data structures storing DOM ids.</p>
<p>Route i) runs the risk of keeping these caches up to date, and in particular avoiding leaks due to &#8220;expired&#8221; DOM nodes continuing to hang around in the cache - but it would probably be faster at runtime. Route ii) will be a little slower (incurs the costs we have been talking about so far, in invoking a document.getElementById equivalent on going to the DOM) but is definitely leak-safe, and might also help others navigate around the DOM.</p>
<h4>What to do</h4>
<p>These are hard kinds of calls to make, and involve a consideration and weighting of different kinds of issues. Currently a reasonable tradeoff for <code>fluid.jById</code> seems to be to go towards <code>document.getElementById</code>, but to put in a guard branch with a hard failure if a &#8220;name&#8221; attribute is picked up by mistake. For &#8220;live&#8221; storage during drag-and-drop, the jQuery data id cache option appears preferable, since we will already be storing various other data on drop targets in addition to what can be discovered in the DOM.</p>
<p>jQuery.data is really pretty fast, I will leave you with a few more timings -</p>
<table border="0">
<tbody>
<tr>
<th></th>
<th>FF2</th>
<th>FF3</th>
</tr>
<tr>
<td>$(&#8221;[id=my-id]&#8220;)</td>
<td>12ms</td>
<td>5.1ms</td>
</tr>
<tr>
<td>bare document.getElementById()</td>
<td>8.5µs</td>
<td>3.2µs</td>
</tr>
<tr>
<td>document.getElementById() with guard</td>
<td>22µs</td>
<td>6.5µs</td>
</tr>
<tr>
<td>jQuery.data cache hit</td>
<td>2.9µs</td>
<td>1.9µs</td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/08/14/finding-things-quickly/feed/</wfw:commentRss>
		</item>
		<item>
		<title>In praise of jQuery.extend</title>
		<link>http://fluidproject.org/blog/2008/08/04/in-praise-of-jqueryextend/</link>
		<comments>http://fluidproject.org/blog/2008/08/04/in-praise-of-jqueryextend/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 16:59:32 +0000</pubDate>
		<dc:creator>antranig</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/?p=50</guid>
		<description><![CDATA[In the interests of aiming towards slightly more bite-sized blog postings, I thought I would share with you some possibly unsuspected gems in a favorite JQuery method I kicked over recently.
Basic extending
jQuery.extend is more commonly seen as part of plugin code - the jQuery plugin model simply works by &#8220;extension&#8221; of the jQuery object itself [...]]]></description>
			<content:encoded><![CDATA[<p>In the interests of aiming towards slightly more bite-sized blog postings, I thought I would share with you some possibly unsuspected gems in a favorite JQuery method I kicked over recently.</p>
<h4>Basic extending</h4>
<p><code>jQuery.extend</code> is more commonly seen as part of plugin code - the jQuery plugin model simply works by &#8220;extension&#8221; of the jQuery object itself to include new methods. For example, here is some code from the JQuery UI dialog plugin:</p>
<pre>$.extend($.ui.dialog.overlay, {
	instances: [],
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(e) { return e + '.dialog-overlay'; }).join(' '),
...</pre>
<p>The <code>extend</code> call is taking the existing <code>jQuery.ui.dialog.overlay</code> object (initially set up to be a <code>{}</code>) and &#8220;mixing in&#8221; a set of properties and functions from an &#8220;immediate hash&#8221;.</p>
<h4>Multiple arguments</h4>
<p>So far, this would account for the powers of a 3-line function, and one which we have all probably independently written for ourselves (certainly in the historical forms of <code>fluid.mixin</code> and <code>RSF.assign</code>). However, where <code>jQuery.extend</code> really shines is in its extensions. Firstly, it will accept any number of arguments - which are just progressively mixed in on top of its first argument:</p>
<pre>$.extend(target, source1, source2, .... sourcen);</pre>
<p>will &#8220;blat&#8221; all the members from the <code>source</code> arguments serially to arrive on top of <code>target</code>.</p>
<h4>Deep copy</h4>
<p>However, the real money of <code>jQuery.extend</code> is in its &#8220;deepCopy&#8221; functionality. Supplying the <code>boolean</code> value of <code>true</code> as the first argument will not just copy properties laid directly on the &#8220;source&#8221; arguments, but recursively copy any properties it finds. Here is some code from the new Fluid core <code>initialiseThat</code> function:</p>
<pre>      that.options = jQuery.extend(true, {}, fluid.defaults(componentName), userOptions);</pre>
<p>This has replaced countless quantities of &#8220;options&#8221; manipulating code from around the different components, some of it quite fiddly and manual, with a single, clear, static policy in one line. The core JQuery <a href="http://docs.jquery.com/Utilities/jQuery.extend">documentation page for jQuery.extend</a> explains this option, but in a way which might easily be missed at a quick reading. As many of the example show, it is typically used for merging &#8220;options&#8221; structures, but it is also invaluable as a plain &#8220;deep copy&#8221; operation, for example forming the basis of Fluid&#8217;s upcoming <a href="http://wiki.fluidproject.org/display/fluid/Component+Model+Interactions+and+API">pure model</a> idiom. Tricks like this help keep down our core library footprint.</p>
<h4>Note on Javascript types</h4>
<p>In such a staggeringly weakly-typed language as Javascript, this kind of useful &#8220;overloading&#8221; is generally impossible. However Javascript is at least blessed with the ability to always distinguish a handful of primitive types (string, boolean, number) from everything else, and so enables useful &#8220;Swiss army knife&#8221; methods like <code>jQuery.extend</code> - luckily it detectably has no meaning to try to be extending a boolean object. One way to perform this type detection is by use of the <code>typeof</code> operator, JQuery itself chooses to use the following test in this situation:</p>
<pre>  if ( target.constructor == Boolean ) {</pre>
<p>Reading through the JQuery source base is highly recommended for people with a few moments to spare, who like to know what people who know what they are doing look like <img src='http://fluidproject.org/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/08/04/in-praise-of-jqueryextend/feed/</wfw:commentRss>
		</item>
		<item>
		<title>About this and that</title>
		<link>http://fluidproject.org/blog/2008/07/21/about-this-and-that/</link>
		<comments>http://fluidproject.org/blog/2008/07/21/about-this-and-that/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 19:24:38 +0000</pubDate>
		<dc:creator>antranig</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Security]]></category>

		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/?p=30</guid>
		<description><![CDATA[This posting will be about the different styles of creating &#8220;components&#8221; or &#8220;objects&#8221; in Javascript, and which styles Fluid is planning to recommend and in what contexts.
Javascript has inherited an &#8220;infusion&#8221; of &#8220;object-oriented&#8221; features grafted at the last moment on its fairly minimal and clear (LISP-inspired) baseline. The resulting language simply has too many ways [...]]]></description>
			<content:encoded><![CDATA[<p>This posting will be about the different styles of creating &#8220;components&#8221; or &#8220;objects&#8221; in Javascript, and which styles Fluid is planning to recommend and in what contexts.</p>
<p>Javascript has inherited an &#8220;infusion&#8221; of &#8220;object-oriented&#8221; features grafted at the last moment on its fairly minimal and clear (LISP-inspired) baseline. The resulting language simply has too many ways of doing the same thing, and numerous features that are downright dangerous and obscure.</p>
<p>Continuing our chats on the performance theme, Colin and I set out to try to find a simple set of recommendations that would lead to code that is not only safe, but readable, maintainable and performant. Particularly, the aim is to cater to requirements of more structured programming, by larger, looser teams sharing components over longer timescales, rather than the &#8220;one-man&#8221;, ephemeral programs for which Javascript is more obviously suited.</p>
<p>In this posting I will cover a full range of &#8220;componentisation&#8221; techniques available in Javascript — from simple namespacing, structural use of closures &mdash; &#8220;scope-ism&#8221;, blending into the new &#8220;that-ism&#8221; that Fluid will promote, and contrasted against the &#8220;traditional&#8221; object-oriented language features (&#8221;this-ism&#8221;) based on <code>this</code> and <code>prototype</code> that we will deprecate, as well as more old-fashioned but performant and clear styles (&#8221;arg-ism&#8221;) carried forward from &#8220;pre-object-oriented&#8221; languages.</p>
<h3>Open and closed</h3>
<p><span id="more-30"></span></p>
<p>Fluid&#8217;s goal is to build platform of components which are not only flexible, but reliable and easy to extend. An important slogan in this area is &#8220;<em><a href="http://en.wikipedia.org/wiki/Open/closed_principle">open for extension, closed for modification</a></em>&#8221; which is traditionally seen in the area of object-orientation.</p>
<p>It is arguable whether Javascript supports object-orientation, or whether this is even a good idea, but the open/closed principle is nonetheless a good one, and clearly expresses the kind of tradeoffs we really want in an increasingly large-scale design – it should be easy to decorate the framework and components with new behaviours, but at the same time, it should be impossible to pervert or &#8220;unexpectedly change the meaning&#8221; of existing code either accidentally or deliberately. It is this latter danger, as we will see later, where Javascript&#8217;s traditional &#8220;OO&#8221; features fall down badly.</p>
<h3>OO or not OO</h3>
<p>Talking about &#8220;object-orientation&#8221; is traditionally dangerous, since each family of languages (C++, Java, Smalltalk, and even Javascript) brings its own particular flavours and assumptions which can make it hard to hold a regular dialogue. When we are talking about strategies for componentisation, we will want to talk more about what goals OO might <em>achieve</em> in an architecture rather than the exact mechanisms it might use. The three corners of OO are traditionally conceived as <em>encapsulation</em>, <em>polymorphism</em>, and <em>inheritance</em> – in a personal view, these have been listed in order of decreasing importance.</p>
<h2><code>this</code>-ism</h2>
<p>Firstly we will look at the features built into the Javascript language traditionally intended to support &#8220;object orientation&#8221; and see what is wrong with them. Syntactically, these look very similar to Java&#8217;s features, but very misleadingly work nothing like them.</p>
<p>Here is a basic Cat:</p>
<pre>function Cat(name) {
  this.name = name;
  }

Cat.prototype.meow = function () {
  alert(this.name + " says Meow!");
  };

var myCat = new Cat("Richard");

myCat.meow();</pre>
<p>This is clearly &#8220;inspired&#8221; by the ability in Java to declare <code>class Cat</code>, but the more one looks into it, the more kinds of slippage one sees. This isn&#8217;t because the Javascript designers didn&#8217;t &#8220;understand&#8221; OO, but because they had initially set out to design a completely different language. In much the same way that Java is completely Object-focused, to the exclusion of functions as first-class citizens, Javascript takes exactly the opposite route, and is completely function-focused, barely recognising Objects at all (except as aggregates).</p>
<p><code>function Cat</code> is called a &#8220;constructor&#8221;, or sometimes, a &#8220;constructor function&#8221;, but for a start it can be seen that very little other than convention distinguishes it from a standalone function. The use of the keyword <code>this</code> is mysterious – what does it refer to? This is actually a piece of magic performed by the <code>new</code> keyword at the time it operates the constructor function call – a new Object is created and bound to the this pointer. &#8220;new&#8221; actually does many other magic things at the same time – it also assigns to a hidden field called the &#8220;prototype&#8221; of the Object under construction, the value of another magic object called &#8220;Cat.prototype&#8221; – every Javascript function comes into existence with a <code>prototype</code> field, &#8220;just on the off chance&#8221; it ends up being used as a constructor (this is a little similar to the way every Java Object comes into existence with a monitor, just in case it is used as a lock :P).</p>
<p>This appears all well and dandy, but &#8220;this-ism&#8221; actually has so much looseness built into it as to be fatally flawed. The central problem is that <em>every</em> function in Javascript is &#8220;<a href="http://www.ddj.com/cpp/184401197">free</a>&#8220;and hence there is no place to store the context of which object it is being invoked on. Therefore the <code>this</code> entry is &#8220;faked up&#8221; every time a function call is invoked, and there are no bounds that could be placed on what kind of object could be a <code>this</code>, or even whether it is supplied at all!</p>
<p>What happens if we forget to call <code>new Cat()</code> but simply say <code>var MyCat = Cat()</code>? Something terrible. For a free function not invoked through a holding Object, Javascript drops <code>this</code> back to hold the &#8220;global object&#8221;, which in a browser is typically the <code>window</code> Object – therefore this function call silently corrupts a piece of global state – there will be no compile-time or run-time warnings.</p>
<h3><code>this</code> hijacking</h3>
<p>Similarly, nothing prevents &#8220;this hijacking&#8221; – for example it is the tiniest effort in the world to follow the code above with this perversion:</p>
<p><code><br />
var myDog = new Dog();<br />
myDog.meow = myCat.meow;<br />
myDog.meow();<br />
</code></p>
<p>The assumptions, whatever they were, in the &#8220;meow&#8221; function above have probably been violated – since Javascript is a &#8220;typeless&#8221; language it would be hard to write down what these assumptions might be in order to enforce them – and if myDog happened to have a field called &#8220;name&#8221; the meow would probably succeed. However, the inability to ever know, when writing (or even reading) a piece of code, which value one can expect to be bound to the &#8220;this&#8221; pointer makes it impossible to write reliable and predictable code with this idiom. A flavour of the kinds of contortions &#8220;this-ism&#8221; forces on coders can be seen when dealing with (browser) event handlers – since these always *are* pure functions, the &#8220;this&#8221; context of any previously bound &#8220;object methods&#8221; which are assigned as handlers becomes lost, and the better Javascript frameworks pride themselves on doing automatic &#8220;this adjustment&#8221; before dispatching to a handler. This sort of thing is fine for frameworks, but is the sort of thing that can easily be &#8220;accidentally&#8221; foisted onto a user as soon as they come to write new components for a framework.</p>
<h4>Note on function naming - capitalisation for constructors</h4>
<p>Note that a useful convention in naming Javascript functions is to reserve those beginning with capital letters only for old-fashioned &#8220;this-ist&#8221; constructors - this can help to head off this-ist disasters caused by forgetting to invoke those functions which require it with <code>new</code>. So we write <code>Cat</code> for the constructor we expect to be used with <code>new Cat()</code>, but later on we will write <code>cat</code> or <code>make_cat</code> for functions with a &#8220;constructive effect&#8221; that don&#8217;t require <code>new</code>.</p>
<h3>Prototype hijacking</h3>
<p>A final &#8220;perversion&#8221; following from this-ism is of &#8220;prototype hijacking&#8221;. Many of the effects (and many unrelated effects) of OO &#8220;inheritance&#8221; can be emulated in Javascript &#8220;this-ism&#8221; by means of assembling a chain of prototype instances.</p>
<pre>SuperCat.prototype = new Cat();

function SuperCat(name) {
  Cat.call(name);
  this.superpower = "fly";
  }

var mySuperCat = new SuperCat("Edward");

mySuperCat.meow();</pre>
<p>This is powerful, just as inheritance is in classically OO languages. However, it is &#8220;too powerful&#8221; – since we have violated the Open/Closed principle. Having happily written our own inheritance hierarchy of Cats, perfectly legal Javascript may subsequently come along and write <code>SuperCat.prototype = new Dog()</code>.</p>
<p>This not only has the devastating effect of causing future SuperCats to in fact become Dogs, it futhermore causes <em>all SuperCats ever created to also retrospectively become Dogs</em>. Thus this changes the meaning not only of the code within SuperCat methods, but the meaning of all client code that has ever used a SuperCat.</p>
<p>This is &#8220;cool&#8221; – in the sense that it is a really cool capability to impress your friends who use other languages – and a cool capability to use in code which just one person is working on (you), when that person has a really good memory and a clear head. It is far from cool when working on a large team, perhaps not all of whom one knows very well, and whose code one has to read and maintain over a long period.</p>
<p>Code that is easy to follow and understand is just another side of the same coin which Fluid calls &#8220;portal-friendliness&#8221; – code is &#8220;portal safe&#8221; if it does not have &#8220;unexpected&#8221; collateral effects on other code, for example by assigning to core language primitives, or similarly in this case changing the meaning of 3rd-party code by dicking around with its inheritance structure.</p>
<h4>Security</h4>
<p>If you believe that a Javascript program can in any way be &#8220;secure&#8221; (which I don&#8217;t, given current environments and practices) the above &#8220;hijacks&#8221; and &#8220;perversions&#8221; can also be seen to be dangerous from a security perspective, in that they allow unintended changes in meaning to 3rd-party code. In upcoming environments such as Google&#8217;s <a href="http://code.google.com/p/google-caja/">Caja</a>, actually secure coding will start to be possible – and it is no coincidence that the first language features to meet the axe will be <code>this</code> and <code>prototype</code>. In<br />
the meantime, you can get a start at <code>this</code>-less coding before the revolution comes, and enjoy at least what security and reliability today&#8217;s Javascript has to offer.<br />
<!--more--></p>
<h2>Arg-ism</h2>
<p>Having considered that Javascript&#8217;s OO features are unusable in the large, we banish this whole infrastructure from our minds (including this, new, prototype and constructor) and begin to look for other ways of coding that will let us achieve some of the same goals.</p>
<p>The first question to ask is, &#8220;do we really need Object Orientation?&#8221;, or more accurately, how could we achieve some of its goals without any particular real assistance from the language?</p>
<h4>The object-oriented features that C has to offer</h4>
<p>My friend Bob and I were once C++ programmers, in the era when C++ held the role as the &#8220;acceptable public face of OO&#8221; – worthy, slightly stodgy, and with possibly worrying performance characteristics. A favorite joke we would share was a phrase once dropped by a particularly capable &#8220;old salt&#8221; programmer who once said that given the choice between C and C++, that he &#8220;preferred the object oriented features that C had to offer&#8221;.</p>
<p>Was this a joke? Is that a question? What *are* the object oriented features that C has to offer? Luckily, whatever they are, they are available in most languages ever written, and many people are indeed happy with them.</p>
<p>A dirty secret is that the &#8220;this&#8221; pointer we are familiar with from C++ and Java is really just a &#8220;hidden function call argument&#8221;. And indeed, the OO calls we started to see in 80&#8217;s C++ evolved directly from their equivalent 70&#8217;s C calls that looked like this:</p>
<pre>typedef struct Cat {
  char* name;
  } Cat;

void meow(Cat* this) {
  printf("%s says Meow!", this-&gt;name);
  }

Cat myCat = {"Richard"};

meow(myCat);</pre>
<p>Oh the good old days. What have we lost here from &#8220;OO&#8221;? Well, we have lost some encapsulation – we cannot hide the details of the struct members from the public, but we could never do that with &#8220;this-ism&#8221; either. So that is no loss. What we have lost is polymorphism – the <code>meow</code> function is statically dispatched, and could not be &#8220;overridden&#8221; to behave differently based on the contents of the <code>this</code> pointer it was handed. In the C days this sort of thing was done with type fields and switch statements, and generally fell down in the &#8220;Open-ness&#8221; stakes – these designs are not sufficiently in some cases &#8220;open for extension&#8221; but at least they don&#8217;t fail to be &#8220;closed for modification&#8221;. Noone could send a non-Cat to our meow function.</p>
<p>However in many cases polymorphism is simply not appropriate in a design – so why should we have to always pay for it? This was one of the early criticisms levelled against C++, which was reponsible for its rather &#8220;neither fish nor fowl&#8221; OO system that didn&#8217;t actually give you polymorphic dispatch unless you asked for it. But what this demonstrates is that this is a perfectly valid compositional technique for many situations – and it has the advantages that it is extremely performant, and easy to follow:</p>
<pre>function makeCat(name) {
  var togo = {name: name};
  }

function cat_meow(cat) {
  alert(cat.name + " says Meow!");
  };

var myCat = makeCat("Richard");

cat_meow(myCat);</pre>
<p>In this little example we see no suffering imposed through &#8220;arg-ism&#8221; and the code is much clearer and will run faster. In a, perhaps strongly &#8220;data-driven&#8221;, design where you are sure no polymorphism or extension through inheritance will be required, C-style componentisation is an approach strongly to be considered. For example, the <a href="http://www2.caret.cam.ac.uk/rsfwiki/Wiki.jsp?page=PrimitiveComponents">RSF component tree</a> idiom is &#8220;closed&#8221; by design – despite forming a hierarchy, it is a hierarchy which is designed purely to classify data, and is &#8220;closed&#8221; in intent, since user code is not intended to be able to create new &#8220;component types&#8221;. Arg-ism would be appropriate for representing and constructing components of this type.</p>
<h2>Scope-ism</h2>
<p>None of our design options so far have actually succeeded on delivering on arguably the most important of the 3 cornerstones of OO, encapsulation. Protecting data from unexpected and asynchronous modification is one of the most important things we can do to make a design more reliable and easier to maintain, through making it easier to reason about the kinds of effects a piece of code might have, and what it could influence.</p>
<p>As most famously proposed by <a href="http://javascript.crockford.com/private.html">Douglas Crockford</a>, the only means of achieving properly private data in Javascript is to go back to its functional roots, and hide these within function closures. If you are not familiar with Javascript&#8217;s closure support, now would be a good time to browse around several of the excellent articles on Crockford&#8217;s site to familiarise yourself.</p>
<h3>Scope-ism for modules</h3>
<p>This is a structuring device which can be used at all levels within a Javascript program. Sometimes the depth of nesting can become somewhat dizzying, but adopting a consistent indentation and coding style can help a lot with this. At the outermost level, we can gain encapsulation for an entire &#8220;module&#8221; by enclosing wide swaths of Javascript code in a closure:</p>
<pre>var Fluid = Fluid || {};

(function () {
  function myPrivateFunction (arg) {
    alert("Your arg was " + arg);
    }

Fluid.myPublicFunction = function() {
    return myPrivateFunction("thing");
    }

  }) ();</pre>
<p>[Note that this, superior, style of module declaration has come to be called "Colinism" – it is a slight variation on the pattern seen in Crockford and other places in that the public namespace object can be "accreted" – it is "guarded" in the first line to ensure that it exists and is at global scope, and then in the anonymous function block it has public members assigned to it one by one]</p>
<p>The definition <code>myPrivateFunction</code> is <em>completely</em> inaccessible to code outside this block, as would any data or other material which was declared in this area. Finally we can achieve &#8220;encapsulation&#8221;, here at the level of an entire &#8220;module&#8221;. Only values which &#8220;escape&#8221; by being assigned to globally visible variables as a result of the block execution can be seen by other code. The global <code>Fluid</code> object can itself be corrupted by having its members modified, but at least the code we write inside <code>myPublicFunction</code> now has the guarantees of a stable environment. If the code executes at all, it will generally do so in a tamper-proof box that makes it much easier to debug and maintain.</p>
<h3>Scope-ism in the smaller</h3>
<p>This concept of a &#8220;module&#8221; is really one again established by convention – Javascript is a &#8220;do it yourself&#8221; language and all these structuring devices are just patterns we agree amongst ourselves. The same kind of encapsulation is also invaluable on smaller scales, creating a kind of structure which doesn&#8217;t really have a name, but is quite typical, for example, in &#8220;<a href="http://www2.caret.cam.ac.uk/rsfwiki/Wiki.jsp?page=InitBlock">init blocks</a>&#8221; which fire on page loads and traverse the DOM to contextualise and attach event handlers to what they find – for example here is the skeleton of an init block I recently wrote:</p>
<pre>  AddParticipants.initChooseRoles = function (baseID, selfTemplate) {
    var base = $jit(baseID);
    var IDtoIndex = {};
    var indexToRow = [];
    indexTable("user-key", base, "tr.role-row", IDtoIndex, indexToRow);
    var checks = base.find(".role-row input");

    var lastChecked; // The "true ID" for the DOM element  

    checks.click(function(event) {
      var checked = $(event.target).attr("checked");
      if (checked) {
        if (lastChecked &amp;&amp; event.shiftKey) {
          var index1 = IDtoIndex[lastChecked];
          var index2 = IDtoIndex[getIDFromDerived(event.target, keyField)];
           ....

}</pre>
<p>We can see the outer level of this function as following the overall module pattern from the last section – the function &#8220;initChooseRoles&#8221; is attached to the global namespace object AddParticipants which is similarly guarded to &#8220;Fluid&#8221; from before. This function now begins by setting up some shared definitions, having found its targets within the DOM – then these definitions, like base, IDtoIndex, indexToRow and lastChecked become &#8220;closed over&#8221; by numerous inner function definitions (typically handlers). We can see this inner function block as a kind of &#8220;Object&#8221; of its own, with private definitions and public effects separated out.<br />
<!--more--></p>
<h2>Scope-ism in the smallest – that-ism</h2>
<p>Our final destination in this journey through Javascript structuring devices is also due to Crockford, is the smallest-scale use of function scopes, that for direct replacement of the faulty &#8220;this-ism&#8221; where we came in. That-ism is alluded to by Crockford on the <a href="http://javascript.crockford.com/private.html">private members</a> page linked above, but is more fully developed in his recent book <a href="http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb">Javascript: The Good Parts</a> in Chapter 5 (all of this book is thoroughly recommended reading).</p>
<p>The answer to a fragile &#8220;identity&#8221; (<code>this</code>) for object methods is to replace them with a function-scoped alternative, which for want of a better non-reserved alternative, Crockford calls &#8220;that&#8221;. &#8220;That-ism&#8221; looks extremely similar to the function scoped examples we have seen before – with only a difference of emphasis. The difference is that we not only close over essentially *one* piece of state, holding the role formerly occupied by a <code>this</code>, but that we also return it from the function itself. So our &#8220;that-ified&#8221; cat example looks as follows:</p>
<pre>function cat(name) {
  var that = {};
  that.name = name;
  that.meow = function () {
    alert(that.name + " says Meow!");

    };

  return that;
  }
var myCat = cat("Richard");

myCat.meow();</pre>
<p>Compare the differences between &#8220;that cat&#8221; and &#8220;this cat&#8221;. The usage is very similar, only we no longer use the pernicious keyword &#8220;this&#8221;. However the definition style is quite different – not being able to leverage prototypalism, we need to physically bind all the CAT methods we require onto each cat instance as we dispense it. In many ways this is &#8220;more&#8221; &#8220;object-oriented&#8221; than what Javascript supplies out of the box, since we have regained the 3rd leg of encapsulation – we could write any number of &#8220;private variables&#8221; and definitions inside the <code>cat()</code> body which would be firmly hidden.</p>
<p>On the face of it this looks like we have had to sacrifice inheritence – but to a large extent we can get this back too. Here is our happy SuperCat:</p>
<pre>function superCat(name) {
  var that = cat(name);
  that.superpower = "fly";
  return that;
  }

var mySuperCat = superCat("Edward");

mySuperCat.meow();</pre>
<p>Simply by &#8220;instance chaining&#8221; we can cascade that-ism from &#8220;constructor&#8221; to &#8220;superconstructor&#8221; and obtain most of the (useful) effects of inheritance. Our design is &#8220;open for extension&#8221; again.</p>
<h3>Drawbacks of that-ism</h3>
<p>The only really significant drawback of that-ism is efficiency. We are literally fabricating new function handles for each of its methods every time we manufacture an object, and this has to be contrasted with the efficiency of this-ism and prototypalism whereby the selfsame function handles are shared amongst all instance of a &#8220;type&#8221;. In theory this overhead could be quite small – the &#8220;closed-over&#8221; data in each method is just the <code>that</code> reference, and with the space for the function handle itself, say in a Java-type VM this would amount to 8n or 16n bytes for an object with n methods. Whether we consider this significant or not would tend to depend on the context – where a &#8220;component&#8221; refers to a user-visible widget that is rendered in a DOM, this expense would be dwarfed by any browser-side or OS-side resources required to represent it. In a more resource-intensive role (perhaps for rendering or data processing) it would probably be unacceptable, and  one would be more prone to fall back upon the most efficient scheme of all, the glorious arg-ism of the 70s.</p>
<h2>Conclusion</h2>
<h4>What to use and when?</h4>
<p>The general recommendation of this article is &#8220;use that, not this&#8221;. This-ism has been argued to be almost universally destructive and not even deliver on the full goals that were staked out for &#8220;object oriented&#8221; designs. For some applications, expecially high-performance and/or data-driven applications, users have been recommended to fall back on &#8220;the object-oriented features which C has to offer&#8221;, being fully argument-driven binding (arg-ism), and where any polymorphism is required to achieve this through duck typing or other data-driven idioms. And overall, to play to Javascript&#8217;s (original) strengths – use function block scopes for storing data and creating &#8220;units with identity&#8221; (objects) rather than Javascript Objects themselves – which last was also the final advice from my performance-oriented posting.</p>
<p>As I speak, Fluid is fully invested in a wholesale conversion from this-ism to that-ism, for which there have been presentation materials at the latest &#8220;Fearless Javascript&#8221; workshops, and also a growing body of <a href="http://wiki.fluidproject.org/display/fluid/How+to+Define+a+Unit">that-ism documentation</a> on the Fluid wiki. Take that!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/07/21/about-this-and-that/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Fearless JavaScript 2.0</title>
		<link>http://fluidproject.org/blog/2008/06/20/fearless-javascript-20/</link>
		<comments>http://fluidproject.org/blog/2008/06/20/fearless-javascript-20/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 21:44:55 +0000</pubDate>
		<dc:creator>colin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/2008/06/20/fearless-javascript-20/</guid>
		<description><![CDATA[Back in April, Eli Cochran and I organized a half-day workshop on JavaScript development techniques at the JA-SIG Spring conference in St. Paul, MN.  Writing Fearless Javascript for Portlets, Widgets, and Portals was designed to give attendees a primer on various aspects of client-side user interface development, including JavaScript fundamentals, the use of toolkits [...]]]></description>
			<content:encoded><![CDATA[<p>Back in April, Eli Cochran and I organized a half-day workshop on JavaScript development techniques at the JA-SIG Spring conference in St. Paul, MN.  <em>Writing Fearless Javascript for Portlets, Widgets, and Portals</em> was designed to give attendees a primer on various aspects of client-side user interface development, including JavaScript fundamentals, the use of toolkits such as jQuery, and DHTML accessibility.</p>
<p>The workshop explores what I&#8217;ve been referring to as &#8220;modern&#8221; JavaScript programming, for lack of a better term. In contrast to the previous generation of JavaScript programs, where small bits of interactivity were sprinkled on top of a largely static document, modern JavaScript involves the creation of richly interactive applications and components. These days, your code probably shares the page and Javascript&#8217;s notorious global namespace with other libraries and widgets. As a result, you need to do things a bit differently to ensure your code is self-contained and won&#8217;t conflict with other libraries. <a href="http://wiki.fluidproject.org/display/fluid/Fearless+JavaScript+Workshop">Fearless JavaScript</a> gives you the techniques needed to thrive in the world of portals, plugins, and mash-ups.</p>
<p>We&#8217;ll be presenting a new edition of Fearless JavaScript at the Sakai Summer 2008 conference in Paris, France. The material has been significantly refined, and we&#8217;ve added another co-presenter: Nicolaas Matthijs from CARET at the University of Cambridge. Nico will be talking about how to create gadgets for Sakai using JSON-based data feeds. We&#8217;re working on some tutorial code that walks you through using Fluid components within a Sakai gadget. Cool stuff.</p>
<p>Nico attended the original Fearless JavaScript workshop in St. Paul, and had lots of interesting questions and suggestions for us. Afterwards, Nico and I spent an enjoyable couple of hours working together on some of his gadgets, tweaking their accessibility and talking about his designs. He&#8217;s doing some great work on MyCamTools, and I&#8217;m looking forward to sharing the stage with him and Eli for Fearless JavaScript 2.0.</p>
<p>If you&#8217;re in Paris for the Sakai conference, we&#8217;d love to see you at the workshop. If you can&#8217;t make it, we&#8217;re hoping to create a podcast of the event. Here are the details:</p>
<p><strong><a href="http://wiki.fluidproject.org/display/fluid/Fearless+JavaScript+Workshop">Fearless JavaScript</a></strong><br />
Presented by Colin Clark, Eli Cochran, and Nicolaas Matthijs<br />
Monday, June 30<br />
1:30 - 4:30 pm in Amphi 55A</p>
<p>Topics will include:</p>
<p>    * Why JavaScript?<br />
    * Fundamentals of JavaScript<br />
    * Using jQuery<br />
    * JavaScript in Sakai<br />
    * Portal and mash-up friendliness<br />
    * Accessibility</p>
<p>Everyone is welcome to attend the workshop. It&#8217;s assumed that you have some understanding of at least one programming language, and that you&#8217;ll bring a laptop to follow along with the hands-on exercises. </p>
<p>See you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/06/20/fearless-javascript-20/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Performance and Design</title>
		<link>http://fluidproject.org/blog/2008/06/16/performance-and-design/</link>
		<comments>http://fluidproject.org/blog/2008/06/16/performance-and-design/#comments</comments>
		<pubDate>Mon, 16 Jun 2008 17:43:16 +0000</pubDate>
		<dc:creator>colin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/2008/06/16/performance-and-design/</guid>
		<description><![CDATA[Following up on Antranig&#8217;s recent post about performance, I&#8217;d like to address the issue of code design and its relationship to performance. Antranig&#8217;s article is very comprehensive and well-considered, and it provides us with a number of guidelines for balancing the tradeoffs between code quality and speed. However, I was surprised that he didn&#8217;t remind [...]]]></description>
			<content:encoded><![CDATA[<p>Following up on Antranig&#8217;s recent post about performance, I&#8217;d like to address the issue of code design and its relationship to performance. Antranig&#8217;s article is very comprehensive and well-considered, and it provides us with a number of guidelines for balancing the tradeoffs between code quality and speed. However, I was surprised that he didn&#8217;t remind us the C.A.R. Hoare quote made famous by Donald Knuth:</p>
<p>
<blockquote>&#8220;Premature optimization is the root of all evil.&#8221;</p></blockquote>
<p>Antranig&#8217;s performance metrics are intended to help establish a gut feel about the cost of a particular operation. They&#8217;re low-level measurements, and as such they can&#8217;t take into account a fundamental variable: context. These performance metrics have very different consequences depending on the size, scale, and nature of the application. His examples are apt: intensive, highly recursive, up-front operations like template rendering show the full cost of JavaScript&#8217;s weak performance. Indeed, Antranig has used his research to good effect on our nascent client-side template renderer. In a relatively short amount of time, he was able to improve the performance of his low-level parsing algorithms by several orders of magnitude using regular expressions and fast string comparisons. Impressive stuff.</p>
<p>On the other hand, context matters a lot when it comes to user-facing behaviour, where timings may vary significantly based on the user&#8217;s choices. Many UI components, such as the Uploader, provide a fairly modal experience for the user. Such components undoubtedly have less stringent performance requirements, and our acceptance criteria should be determined by testing in real-world situations.</p>
<p>The risk with out of context performance measurements is the tendency to optimize prematurely and without accurate data. There&#8217;s only so much time in the day. Don&#8217;t lose the opportunity to add useful features to your application by starting in on time-intensive performance optimizations too early. Without good data, your hard work may only have a tiny impact on the overall perception of speediness. Worse yet, premature optimization can lead towards architectures that are poorly factored, redundant, and hard to maintain.</p>
<p>So how do we ensure good performance without compromising architectural quality?</p>
<ol>
<li>Write code with good design principles in mind</li>
<li>Continually measure performance in real world situations</li>
<li>Refine code incrementally to improve performance</li>
</ol>
<p>Let&#8217;s take jQuery as an example. If you look at the <a href="http://code.jquery.com/jquery-1.0.js">first release of jQuery</a>, you&#8217;ll find that it was mostly composed of small functions that are clear and easy to read. jQuery&#8217;s author, John Resig, has always done a very good job of carefully profiling his code with performance tests, and over time the code base has evolved in certain areas to be faster and, as a concequence, occasionally less readable. He took the time to build something real first, then he optimized strategically. This is exactly the example of how we should all handle performance optimizations: build it cleanly, then identify areas where performance optimizations are necessary. Optimization without real-world numbers is, well, evil.</p>
<p>Building on Antranig&#8217;s advice, here are some strategies to help ensure both good performance and a maintainable design in JavaScript:</p>
<h2>Avoid deep inheritance hierarchies</h2>
<p>Excess use of inheritance tends to be brittle, hard to reuse, and slow. In JavaScript, inheritance is prototypal: an object has a secret prototype link that points to its parent object. When a property isn&#8217;t found on an instance directly, the object&#8217;s prototype is searched, then the prototype&#8217;s prototype, and onwards up the inheritance chain. This can be extremely slow on objects with a long lineage. JavaScript provides more effective strategies for reuse, such as containment and dynamic mix-ins. You&#8217;re better off with a very shallow inheritance hierarchy, using these techniques to share code across objects instead.</p>
<h2>Break code into small, independent parts</h2>
<p>JavaScript is a functional language, and functions serve as the fundamental building block for all programs. Break complicated algorithms up into smaller functions that take only the data necessary to perform a given operation. Small functions are more easily tested, modified, and reused. What about the cost per function call that Antranig mentions? If you need to optimize for speed later, you can easily merge several functions back into one. Analyze frequent code paths and identify specific bottlenecks first, then selectively fold smaller functions into a larger one.</p>
<h2>Don&#8217;t deeply nest functions</h2>
<p>In JavaScript, functions can be nested inside other functions. This is a very powerful technique, since inner functions have access to the variables and scope of the outer function even after the outer function has finished executing. This is called closure, and it&#8217;s one of the best ways to encapsulate state and behaviour in JavaScript. The trick is to avoid deep nesting; don&#8217;t stick a function inside a function inside a function. Similar to the inheritance chain, each JavaScript function invocation brings with it a scope chain, providing access to variables defined in outer functions. If a reference to a particular variable isn&#8217;t found inside a function&#8217;s scope, the JavaScript runtime will climb the scope chain, searching each outer scope in turn to find the property. All this searching can get pretty slow. Limit yourself to a couple of layers of closure at the most. Here&#8217;s a slight contrived code example and an illustration of the scope chain in action:
<p><strong>Illustrated Code Example: Using a closure for event handling</strong></p>
<pre>
  function showMessage(messageToDisplay) {
  	var todaysPie = "Banana creme pie";

	return function(event) {
		alert(messageToDisplay + " " + todaysPie);
		showPictureOfPie(event.target, todaysPie);
	}
  }

  var messageClickHandler = showMessage("Welcome to my pie shop. Today's pie is:")
  $(element).click(clickHandler);
</pre>
<p>
<img src="http://wiki.fluidproject.org/download/attachments/3342621/JavaScript-Call-Stack.png" />
</p>
<h2>Identify nameable units of behaviour and encapsulate them</h2>
<p>On the client side, it&#8217;s really easy to let your application logic get all muddled up with your presentation code. Large, hard to maintain functions are often structured like this: 1) Perform some calculations; 2) fetch some data; 3) update the DOM. These are separate tasks, and your code will be significantly easier to read and reuse if you split these behaviours into independent units. The trick is to look at your code while you&#8217;re writing it and recognize &#8220;things&#8221; that are easily identified and named. Using a closure or an object, you can factor out pieces of the overall behaviour and data into a separate entity. Here&#8217;s an example of the various units of behaviour we identified within the Reorderer:</p>
<p></p>
<ul>
<li>The Reorderer is responsible for binding events to DOM elements and providing end-user APIs</li>
<li>A Layout provides an awareness of visual layout and spatial characteristics: grids, lists, portlets within columns, and so on</li>
<li>The Mover is responsible for moving elements around in the DOM, deferring to the Layout for spatial information</li>
<li>A Permissions object defines the rules for valid drop targets and operations on a specific element</li>
<li>Keyboard selections and accessibility is provided by the jQuery keyboard-a11y plugin</li>
<li>MouseDragAndDrop encapsulates our use of jQuery UI for low-level drag and drop functionality</li>
</ul>
<h2>Use closures to encapsulate data and behaviour</h2>
<p>Antranig covered this one really well in his post. Under many circumstances, you&#8217;ll pay a significantly lower cost to access data wrapped in a closure than within an object, and functional idioms tend to be more flexible and easier to maintain than object-oriented ones. This is particularly true in JavaScript, where there is no built-in support for namespaces or privacy. Just be careful not to nest your closures too deeply.</p>
<h2>Never, ever cut and paste code</h2>
<p>It almost feels silly to repeat this one here. One of the foundational principles of programming, regardless of the language you&#8217;re using, is DRY: <a href="http://c2.com/cgi/wiki?DontRepeatYourself">Don&#8217;t Repeat Yourself</a>. The bottom line is this: cut and pasted code will come back to bite you. Don&#8217;t do it. Antranig&#8217;s post hints at the idea that it&#8217;s okay to cut and past code in JavaScript. For all but the most extreme cases, I don&#8217;t buy it. If you find yourself tempted to cut and paste something, take the time to factor it into a function. It will be easier to update later, and much easier to test. Duplicate code hurts!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/06/16/performance-and-design/feed/</wfw:commentRss>
		</item>
		<item>
		<title>&#8220;How Long, Oh Lord?&#8221;</title>
		<link>http://fluidproject.org/blog/2008/05/30/how-long-oh-lord/</link>
		<comments>http://fluidproject.org/blog/2008/05/30/how-long-oh-lord/#comments</comments>
		<pubDate>Fri, 30 May 2008 13:43:56 +0000</pubDate>
		<dc:creator>antranig</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/2008/05/30/how-long-oh-lord/</guid>
		<description><![CDATA[Recently, I expressed to Colin the sense of &#8220;disorientation&#8221; every Java (or other &#8220;traditional&#8221;) programmer must feel at diving into the client side and trying to write idiomatic, performant code. Every reasonable coder quickly develops a &#8220;gut&#8221; feeling for the costs (both in design, and resources) for the various primitives they have at their disposal. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I expressed to Colin the sense of &#8220;disorientation&#8221; every Java (or other &#8220;traditional&#8221;) programmer must feel at diving into the client side and trying to write idiomatic, performant code. Every reasonable coder quickly develops a &#8220;gut&#8221; feeling for the costs (both in design, and resources) for the various primitives they have at their disposal. For timings, which is mainly what I am going to talk about in this posting, this might not take the form of actual hard numbers, but certainly a kind of &#8220;order of magnitude&#8221; relative estimate.</p>
<p>What I mean here is to know, generally within a factor of 2 or 3, how much one operation is likely to cost relative to another one, and to have a similar kind of &#8220;fuzz factor&#8221; with respect to actual performance on a particular kind of machine you are familiar with. Back in the days when I was starting on <a HREF="http://www2.caret.cam.ac.uk/rsfwiki">RSF</a>, pinned to my desk was the original &#8220;How Long, Oh Lord?&#8221; which I reproduce here:</p>
<table CLASS="" SUMMARY="Java performance benchmarks circa 2005" STYLE="margin-left: auto; margin-right: auto; font-size: 1.20em">
<tr>
<th COLSPAN="2" COLSPAN="2" COLSPAN="2" COLSPAN="2" CLASS="" COLSPAN="2" COLSPAN="2" COLSPAN="2" COLSPAN="2">How Long, Oh Lord?</th>
</tr>
<tr>
<td CLASS="">Method Call</td>
<td CLASS="">8ns</td>
</tr>
<tr>
<td CLASS="">ThreadLocal Get</td>
<td CLASS="">60ns</td>
</tr>
<tr>
<td CLASS="">Constructor</td>
<td CLASS="">100ns</td>
</tr>
<tr>
<td CLASS="">Reflective Call</td>
<td CLASS="">700ns</td>
</tr>
</table>
<p>For reference, these timings were on a Windows JDK 1.4 running on a relatively weak machine in 2005, perhaps something like a c.2Ghz P4.</p>
<p>Anyway, to skip to the present, starting work on the RSF/Fluid client-side renderer, I felt similarly at sea on how to plan for a design that runs efficiently. Javascript is starting to emerge from its &#8220;ghetto folkloric&#8221; period and to become the target of determined engineering efforts, and there are a number of resources round the web focused on Javascript performance issues, such as John Resig&#8217;s excellent blog entry collection <a HREF="http://ejohn.org/blog/tags/performance/">http://ejohn.org/blog/tags/performance/</a>, and a splendid presentation by Julien Lecomte of YUI <a HREF="http://yuiblog.com/blog/2007/12/20/video-lecomte/">http://yuiblog.com/blog/2007/12/20/video-lecomte/</a>.</p>
<p>Some of the &#8220;learnings&#8221; I report here in &#8220;How Long, Oh Lord 2008&#8243; are part of Julien&#8217;s presentation, but others I have not seen before. The workhorse of these estimates is a microbenchmark collection I have put together at https://source.caret.cam.ac.uk/rsf/projects/RSFSamples/trunk/AjaxJSON/src/webapp/content/templates/perftest.html (this is just accidentally for now embedded in the middle of a wider Java/RSF/JSON/Maven development structure).</p>
<p>The benchmarks are run in (currently 5) &#8220;batches&#8221; of say 10,000 iterations, the most extreme measurements are discarded, and the average of the remaining three batches are reported as a headline figure. This is an attempt to defeat random variation caused by system business, GC collections and the like.</p>
<p>Here is a sample row and table output from the system:</p>
<style> .bench th, .bench td {border:1px solid #000;} .bench th {background-color:#696969;color:#fff;}/*dark gray*/ .bench td {text-align:left;} .bench th {text-align:left;} </style>
<table SUMMARY="Example of output from JavaScript benchmark tests." CLASS="bench">
<thead>
<th CLASS="">Count</th>
<th CLASS="">Name</th>
<th CLASS="">1</th>
<th CLASS="">2</th>
<th CLASS="">3</th>
<th CLASS="">4</th>
<th CLASS="">5</th>
<th CLASS="">Median ave</th>
</tr>
<tr>
<td CLASS="">100000</td>
<td CLASS="">Bare Function Call</td>
<td CLASS="">125.0ms: (1.250us/call)</td>
<td CLASS="">93.00ms: (0.930us/call)</td>
<td CLASS="">94.00ms: (0.940us/call)</td>
<td CLASS="">109.0ms: (1.090us/call)</td>
<td CLASS="">110.0ms: (1.100us/call)</td>
<td CLASS="">104.3ms: (1.043us/call)</td>
</tr>
</table>
<h2>Function Calls Considered Harmful</h2>
<p>I think the most central result I want to report here is the truly fantastic expense of function calls in Javascript, which to my mind generally cuts at the heart of the possibility of orderly development.</p>
<p>The bad news is that a simple function call costs around 3 microseconds on a typical machine in Firefox 2.x. Opera builds are generally much better, around the 1µs mark. The &#8220;better&#8221; news going forwards is that current builds of Firefox 3 betas are vastly improved, down to 350ns on the same hardware. All the same, the ground reality is that in the vast majority of installed system for a number of years, a Javascript function call is going to cost something in the region of 1 microsecond. Let&#8217;s put that figure into perspective with a tour of our glorious history - the heroic <a HREF="http://www-03.ibm.com/ibm/history/exhibits/mainframe/mainframe_PP2030.html">IBM System/360 Model 30</a> (Announced April 7, 1964) had a machine cycle time of 1 microsecond. On the personal computer front, the <a HREF="http://oldcomputers.net/pet2001.html">Commodore PET</a> (January 1977) was the same. In this respect (and some others) therefore Javascript sets back computer science 30 years or more. This is a little tongue-in-cheek - but not entirely. Clearly even on the most up-to-date environment, a function call in Java, say, will not execute in a single machine cycle. But the discrepancy is more like 1 order of magnitude, rather than 3 as it is in Javascript.</p>
<p><center><br />
<a HREF="http://www-03.ibm.com/ibm/history/exhibits/mainframe/mainframe_PP2030.html"><img SRC="http://ponder.org.uk/public/IBM-30.jpg" /></a><br />
</center></p>
<h3>Why is this, and what does it mean?</h3>
<p>Javascript function calls, as the most skilled practitioners of Javascript (<a HREF="http://www.crockford.com/javascript/javascript.html">Crockford</a>, etc.) will explain, are vastly powerful, vastly underappreciated pieces of machinery. Every invocation of a Javascript function brings into existence a highly complex structure, a dynamic scope chain which will allow variables to be referenced long after a function has returned — or else, require them to be garbage collected, piece by piece. Therefore a JS &#8220;stack frame&#8221; is really very much more like an &#8220;object&#8221; in a classic &#8220;OO&#8221; language in its capabilities. More on this later. This means that a truly efficient implementation of JS function calls is essentially impossible - although the Firefox 3 team are having a thoroughly good try. What is particularly happy about this situation is that, as Crockford frequently laments, the true power of Javascript functional expressiveness is lost on 99% of its practitioners, who are typically trained if at all) in far less mind-bending idioms. And for those 1% who do truly understand what a JS function call could do, how many can make more than a handful of the function calls they write count for their full power? <img src='http://fluidproject.org/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>What does this mean? It means that truly performant Javascript code is really obliged to drop back more than decades in its structural idiom. The function call is the primary, the first and most useful, unit of modular abstraction in programming, and these costs imply that efficient Javascript code must degrade to consist of few, extremely large function bodies, whereas a design based on fine-grained, flexibly composed units would be much more comprehensible and easy to maintain.</p>
<p>The most skilled Javascript programmers, framework authors, have been aware of this (implicitly or explicitly) for a long while, and it is clear that their code is following suit. As one example, <a HREF="http://code.google.com/p/trimpath/wiki/JavaScriptTemplates">TrimPath Templates</a> a very performant macro-style templating language, is implemented with a large work-horse method (actually TrimPath uses a number of other performance tricks which will be touched upon later). As another, <a HREF="http://jquery.com">JQuery</a>&#8217;s central workhorse, JQuery.find() is likewise a single monster method. In this and many other areas, &#8220;stupider is better&#8221; is often the correct answer - cut and paste, traditionally the anathema of programming, has a new lease of life in Javascript as it is frequently superior to simply repeat frequently occurring, especially small, snippets of code, rather than factor them into function calls.</p>
<h2>Scoping and storing bugbears</h2>
<p>The pattern of which operations in Javascript are performant and which are not is interestingly skew. To go into other results from &#8220;perftest&#8221;, we can discover a rule of thumb that one object property access is roughly equivalent to four string comparisons. For example, when testing a string value to be one of four possible values, looking it up as an Object member is roughly breaking even with writing out the sequential comparisons.</p>
<p>Similarly, access to objects in outer scopes carries a price. For example, again on FF2.x, simply accessing a variable not declared at the current function scope carries a penalty of 300ns. Vast, in &#8220;traditional&#8221; terms.</p>
<p>Facts like this militate for numerous &#8220;hoisting&#8221; tricks - essentially if a given expression or variable is accessed more than a single time in a particular function scope, it will almost always make sense to assign it to a local variable before use. This is obviously much more important for Object members than for &#8220;outer scope&#8221; variables. Julien Lecomte covers this in his presentation - a further comparison worth noticing is that function scopes are actually more more efficient containers for data than Objects. This further pushes forwards the Crockfordian view of &#8220;function scopes&#8221; as being the primary units of abstraction and storage in an &#8220;idiomatic Javascript&#8221; program, rather than traditional &#8220;Objects&#8221;. If one is going to pay 1 microsecond for a function call, better make it count - but better to pay 3 microsecond for a call and 300 ns for an access, than to pay 5 microseconds to construct an Object and then 500 ns per access (Firefox 2.x figures - FF3 and Opera are better, but the relative picture is unchanged).</p>
<h3>An unfortunate discovery</h3>
<p>On Firefox 2.x the already dim picture is muddied further by the discovery that simply invoking a function declared at another function scope nearly doubles the cost - even if no variables are declared or accessed at the outer scope. Since this &#8220;trick&#8221; is the now standard modern recommdation for implementing <a HREF="http://javascript.crockford.com/private.html">namespacing</a> (Crockford on Privacy) this automatically penalises those who seek to organise their code better. Again blissfully this penalty is gone from Firefox 3.</p>
<h2>Finding performant primitives</h2>
<p>Some Javascript operations essentially retain near-native performance. Boolean tests, numeric operations, local control structures such as loops and branches, all proceed pretty quickly. This would seem to at least allow the possibility of some high-performing algorithms (assuming they were structured as giant function blocks) were it not for another really unfortunate Javascript feature - the lack of any bulk &#8220;primitive&#8221; storage. Java&#8217;s primitive array support was often widely derided as a really irritating and unorthogonal language feature, but actually is the only thing that saves it as a data processing language. In Javascript one has only Strings - and even a simple charAt() call causes a complete object instantiation (as a side tip - use of the less-well-known String.charCodeAt() followed by a (much less readable) numeric test is around 20% faster than a charAt() plus String test). There is simply nowhere to put extensive data since every Array is an Array of Object.</p>
<p>This leaves one to fall back on Strings and String tricks. An interesting discovery is that String.indexOf() is a startlingly rapid operation - after what appears to be a standard &#8220;native call overhead&#8221; of something like 1.5 microseconds (abouthalf a &#8220;standard function call&#8221;) (again FF 2.x), the actual search occurs at fully native speeds. This implies you can find a given String amongst around 10K of data practically as fast as you can find it amongst 100 bytes. TrimPath makes very fruitful use of indexOf to gain a very good speed boost, helped by its simple and &#8220;easily recognisable&#8221; templating format.</p>
<p>Regexes can take up a lot of slack in some cases, but their overhead is very much higher than an indexOf. As Lecomte notes, a Regexp.test() is *somewhat* faster than a Regexp.exec() but actually not startlingly so, since the test() appears to require no &#8220;user-visible&#8221; memory allocation. Any Regexp invocation carries a standard overhead of about 2 function calls, so use with care on simple tasks.</p>
<h2>Garbage in, garbage out</h2>
<p>Investigating the costs of garbage in Javascript rounds out most of this discussion. It is very interesting to repeat the performance tests on a &#8220;huge browser image&#8221; runtime, since this immediately exposes the kinds of operations which create garbage and those which do not. I am somewhat untypical in that I am frequently running a system with around 70 top-level Opera frames (it is the only browser that will cope with this sensibly) and perhaps 20 Firefox frames. In a browser image like this, the fact that all Javascript objects are typically thrown into a global shared heap, rather than the per-frame heaps one might perhaps wish for is painfully exposed. Running perftest.js in a &#8220;mega-Opera&#8221; shows the allocating tests running perhaps 100 times slower - the data becomes very spiky, but a single micro-test can end up taking a full millisecond rather than a microsecond.<br />
This exposes that although function calls are &#8220;like&#8221; Object (heap) allocations, they are still underlyingly dealt with by different, and more efficient data structures - even in a &#8220;mega-Opera&#8221;, a bare function call is still taking 1 microsecond, whilst a true heap allocation is running at a millisecond or more. &#8220;mega-Opera&#8221; is a highly untypical environment, but it demonstrates at extremes the superior scaling costs of function frames over true garbage.</p>
<p>If there is a simple take-home message from all of this, it is -</p>
<p>i) Javascript function calls are hugely expensive compared to traditional environments, take great care not to factor your code too deeply,</p>
<p>ii) Javascript function calls are sufficiently powerful to take over many of the traditional roles of &#8220;Objects&#8221; in traditional environments, so consider designs that operate closure-based storage and reserve your true Objects for data transfer,</p>
<p>iii) make judicious use of the primitive operations which are provided (indexOf and regexps) where possible to make your code run reasonably.</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/05/30/how-long-oh-lord/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Shiny new API for the Reorderer</title>
		<link>http://fluidproject.org/blog/2008/05/29/shiny-new-api-for-the-reorderer/</link>
		<comments>http://fluidproject.org/blog/2008/05/29/shiny-new-api-for-the-reorderer/#comments</comments>
		<pubDate>Thu, 29 May 2008 16:19:17 +0000</pubDate>
		<dc:creator>colin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/2008/05/29/shiny-new-api-for-the-reorderer/</guid>
		<description><![CDATA[We&#8217;re really close to putting out Fluid Infusion 0.3. It&#8217;ll be ready in a few days, and is shaping up to be a pretty solid release. In addition to a preview version of the Uploader, we&#8217;ve really improved the user experience and functionality of the Reorderer. We&#8217;ve added sortable layouts, customizable drag-and-drop interactions, and support [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re really close to putting out Fluid Infusion 0.3. It&#8217;ll be ready in a few days, and is shaping up to be a pretty solid release. In addition to a preview version of the <a href="http://wiki.fluidproject.org/display/fluid/Uploader">Uploader</a>, we&#8217;ve really improved the user experience and functionality of the Reorderer. We&#8217;ve added <a href="http://build.fluidproject.org/sakai-imagegallery-tool/sample-code/reorderer/portal/portal.html">sortable layouts</a>, customizable <a href="http://uidesignpatterns.org/content/drag-and-drop">drag-and-drop interactions</a>, and support for all kinds of portal-y features like locking and efficient keyboard navigation. </p>
<p>One of the things we&#8217;ve needed to improve in the Reorderer is the API. In earlier versions, it was pretty hard to initialize your own Reorderer. You needed to know a lot about the inner workings of objects such as LayoutHandlers, item finders, and so on. Infusion 0.3 solves this problem by providing clean, one-line functions for creating your favourite configurations of the Reorderer:</p>
<p><strong>Sorting Lists</strong></p>
<p><code>fluid.reorderList(containerSelector, itemSelector, orderChangedCallback, options);</code></p>
<p>Pass in a selector string to locate your list and the items within it, and you&#8217;ve got yourself an accessible, sortable list. Optionally, you can also specify a callback function that will be invoked every time the list order changes, along with a whole raft of other options for configuring the Reorderer.</p>
<p><strong>Sorting Grids</strong></p>
<p><code>fluid.reorderGrid(containerSelector, itemSelector, orderChangedCallback, options);</code></p>
<p>Same thing. Just pass in a selector string to locate your grid and the items within it, along with an optional order changed callback and some configuration options. Boom, a sortable 2D grid.</p>
<p><strong>Sorting Layouts</strong></p>
<p><code>fluid.reorderLayout(containerSelector, layoutSelectors, orderChangedCallback, options);</code></p>
<p>This one is for reordering portlets, content blocks, or other chunks of layout on a page. Pass in a selector to locate the container of your layout. Pass in an object that contains two selectors: one for the columns in the layout and one for the portlets. This function will do all the heavy lifting for you, figuring out which portlets are in each column, building a Layout object, and so on.</p>
<p>If you want all the advanced portal features of the Layout Customizer, such as locking, JSON-based layout, and permissions, you can always drop down to the lower-level API:</p>
<p><code>fluid.initLayoutCustomizer(layout, permissions, orderChangedURL, options);</code></p>
<p>This function exposes some of the more complex objects used by the Layout Customizer, the Layout and Permissions objects. The Layout is a JSON-style object representing the column and portlet structure in a DOM-agnostic way. Permissions is a complex data structure encoding all of the valid drop target permissions for each portlet and column in the layout. Generally, you&#8217;ll want to use the simpler fluid.reorderLayout() function unless you need the advanced portal features.</p>
<p><strong>Documentation</strong></p>
<p>We realize that code examples and the occasional blog post aren&#8217;t nearly enough to get you started using Infusion. Anastasia has been experimenting with some great new documentation for the 0.3 release. It&#8217;s still very much a work in progress, but check out her <a href="http://wiki.fluidproject.org/display/fluid/Using+the+Reorderer">live examples of how to use the Reorderer</a>. She&#8217;s still figuring out  the right recipe for our documentation, so please share your ideas and thoughts with her!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/05/29/shiny-new-api-for-the-reorderer/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Welcoming Jess Mitchell, Fluid&#8217;s New Project Manager</title>
		<link>http://fluidproject.org/blog/2008/05/11/welcoming-jess-mitchell-fluids-new-project-manager/</link>
		<comments>http://fluidproject.org/blog/2008/05/11/welcoming-jess-mitchell-fluids-new-project-manager/#comments</comments>
		<pubDate>Sun, 11 May 2008 23:06:41 +0000</pubDate>
		<dc:creator>colin</dc:creator>
		
		<category><![CDATA[Community]]></category>

		<category><![CDATA[Project coordination]]></category>

		<guid isPermaLink="false">http://fluidproject.org/blog/2008/05/11/welcoming-jess-mitchell-fluids-new-project-manager/</guid>
		<description><![CDATA[I&#8217;ve been waiting for over a year to write this blog post. I&#8217;m extremely excited to welcome Jess Mitchell on board as our new project manager for Fluid. Earlier this week, Jutta Treviranus sent out a great introduction to Jess  on the fluid-work mailing list. Here&#8217;s a quick excerpt:
&#8220;Jess comes with an incredibly rich [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been waiting for over a year to write this blog post. I&#8217;m extremely excited to welcome Jess Mitchell on board as our new project manager for Fluid. Earlier this week, Jutta Treviranus sent out a <a href="http://fluidproject.org/pipermail/fluid-work/2008-May/001791.html">great introduction to Jess</a>  on the <a href="http://fluidproject.org/mailman/listinfo/fluid-work">fluid-work mailing list</a>. Here&#8217;s a quick excerpt:</p>
<blockquote><p>&#8220;Jess comes with an incredibly rich and relevant background in managing large, complex, distributed projects. She is very familiar with the academic environment, the schools engaged in Fluid and the open source and community source development process. Until recently, Jess was the Innovative Projects Manager at Duke University and managed, among many innovative projects, the Duke Digital Initiative.&#8221;</p></blockquote>
<p>I&#8217;m impressed with how diverse Jess&#8217; background is. She has a firm grasp of technical issues and was a volunteer with the Geekcorps project to <a href="http://en.wikipedia.org/wiki/Ghana_Internet_Exchange">build independent network infrastructure in Ghana</a>. She&#8217;s managed a variety of projects in a higher ed setting, and has taught project courses at Duke University. Her academic background in Political Science and Philosophy  brings a unique perspective on community building and open source culture. And I know she&#8217;s been learning a ton about inclusive design, too!</p>
<p>A quick bit of history: Fluid has been trying to hire a dedicated Project Manager for over a year now. Hiring at a university can be pretty slow and bureaucratic, and we had several promising candidates who were unexpectedly wooed away by offers from the private sector. Throughout this process, we took the time to be sure that we hired someone who will thrive within the unique constraints of a distributed, community-driven environment. I&#8217;m thoroughly confident that Jess will excel in this role, and she is committed to helping us communicate and collaborate better as our community grows.</p>
<p>On a personal level, I&#8217;m relieved by the prospect of being able to focus on technical leadership for Fluid. With all the task-juggling and cat-herding I&#8217;ve done over the past year and a half, it&#8217;s been hard to put enough attention towards architecture and coding. Now that Jess is on board, I&#8217;ll be much more focused on development work. I have a backlog of technical writing and coding to catch up with, so expect to hear a lot more from me on the lists and this blog with code examples, screenshots of new components, and more. </p>
<p>Jess will be based in Boston, but is planning to do a fair bit of traveling over the next few months. She&#8217;s also really interested in hearing from members of the community, so don&#8217;t hesitate to <a href="mailto:&#106;&#101;s&#115;&#109;&#105;&#116;&#99;&#104;&#101;&#108;&#108;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;m">drop her a line</a>. Please join me in welcoming Jess to the Fluid community!</p>
]]></content:encoded>
			<wfw:commentRss>http://fluidproject.org/blog/2008/05/11/welcoming-jess-mitchell-fluids-new-project-manager/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
