<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mozilla Hacks - the Web developer blog &#187; TraceMonkey</title>
	<atom:link href="http://hacks.mozilla.org/category/tracemonkey/feed/" rel="self" type="application/rss+xml" />
	<link>http://hacks.mozilla.org</link>
	<description>hacks.mozilla.org</description>
	<lastBuildDate>Wed, 08 Feb 2012 22:52:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Firefox 4 Performance</title>
		<link>http://hacks.mozilla.org/2011/03/firefox4-performance/</link>
		<comments>http://hacks.mozilla.org/2011/03/firefox4-performance/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 13:00:10 +0000</pubDate>
		<dc:creator>stormy</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Firefox 4]]></category>
		<category><![CDATA[JägerMonkey]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=7528</guid>
		<description><![CDATA[Dave Mandelin from the JS team and Joe Drew from the Graphics team summarize the key performance improvements in Firefox 4. The web wants fast browsers. Cutting-edge HTML5 web pages play games, mash up and share maps, sound, and videos, show spreadsheets and presentations, and edit photos. Only a high-performance browser can do that. What [...]]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://blog.mozilla.com/dmandelin/">Dave Mandelin</a> from the JS team and <a href="http://blog.mozilla.com/joe/">Joe Drew</a> from the Graphics team summarize the key performance improvements in Firefox 4.</em></p>
<p>The web wants fast browsers. Cutting-edge HTML5 web pages <a href="http://dougx.net/plunder/plunder.html">play</a> <a href="http://marblerun.at/tracks/new"> games</a>, <a href="http://googlemapsmania.blogspot.com/">mash up and share maps</a>, <a href="http://vocamus.net/dave/?p=1092">sound</a>, and <a href="http://people.mozilla.com/~prouget/demos/DynamicContentInjection/play.xhtml">videos</a>, show spreadsheets and presentations, and <a href="http://people.mozilla.com/~vladimir/demos/darkroom/darkroom.html">edit photos</a>. Only a high-performance browser can do that. What the web wants, it&#8217;s our job to make, and we&#8217;ve been working hard to make Firefox 4 fast.</p>
<p>Firefox 4 comes with performance improvements in almost every area. The most dramatic improvements are in JavaScript and graphics, which are critical for modern HTML5 apps and games. In the rest of this article, we&#8217;ll profile the key performance technologies and show how they make the web that much &#8220;more awesomer&#8221;.</p>
<p><strong>Fast JavaScript: Uncaging the J&auml;gerMonkey</strong><br />
JavaScript is the programming language of the web, powering most of the dynamic content and behavior, so fast JavaScript is critical for rich apps and games. Firefox 4 gets fast JavaScript from a beast we call <strong><a href="http://www.blogcdn.com/downloadsquad.switched.com/media/2010/11/jagermonkeypostcard.jpg">J&auml;gerMonkey</a></strong>. In techno-gobbledygook, J&auml;gerMonkey is a multi-architecture per-method JavaScript JIT compiler with 64-bit NaN-boxing, inline caching, and register allocation. Let&#8217;s break that down:</p>
<ul>
<em>Multi-architecture<br />
</em>J&auml;gerMonkey has full support for x86, x64, and ARM processors, so we&#8217;re fast on both traditional computers and mobile devices. W00t!<br />
(Crunchy technical stuff ahead: if you don&#8217;t care how it works, skip the rest of the sections.)
</ul>
<ul><em><br />
Per-method JavaScript JIT compilation</em><br />
The basic idea of J&auml;gerMonkey is to translate (<em>compile</em>) JavaScript to machine code, &#8220;just in time&#8221; (JIT). JIT-compiling JavaScript isn&#8217;t new: previous versions of Firefox feature the TraceMonkey JIT, which can generate very fast machine code. But some programs can&#8217;t be &#8220;jitted&#8221; by TraceMonkey. J&auml;gerMonkey has a simpler design that is able to compile everything in exchange for not doing quite as much optimization. But it&#8217;s still fast. And TraceMonkey is still there, to provide a turbo boost when it can.</p>
</ul>
<ul>
<em>64-bit NaN-boxing</em><br />
That&#8217;s the technical name for the new 64-bit formats the JavaScript engine uses to represent program values. These formats are designed to help the JIT compilers and tuned for modern hardware. For example, think about floating-point numbers, which are 64 bits. With the old 32-bit value formats, floating-point calculations required the engine to allocate, read, write, and deallocate extra memory, all of which is slow, especially now that processors are much faster than memory. With the new 64-bit formats, no extra memory is required, and calculations are much faster. If you want to know more, see the technical article <a href="http://blog.mozilla.com/rob-sayre/2010/08/02/mozillas-new-javascript-value-representation/">Mozilla&#8217;s new JavaScript value representation</a>.
</ul>
<ul>
<em>Inline caching</em><br />
Property accesses, like <code>o.p</code>, are common in JavaScript. Without special help from the engine, they are complicated, and thus slow: first the engine has to search the object and its prototypes for the property, next find out where the value is stored, and only then read the value. The idea behind inline caching is: &#8220;What if we could skip all that other junk and just read the value?&#8221; Here&#8217;s how it works: The engine assigns every object a <em>shape</em> that describes its prototype and properties. At first, the JIT generates machine code for <code>o.p</code> that gets the property by laborious searching. But once that code runs, the JITs finds out what </code>o</code>'s shape is and how to get the property. The JIT then generates specialized machine code that simply verifies that the shape is the same and gets the property. For the rest of the program, that <code>o.p</code> runs about as fast as possible. See the technical article <a href="http://blog.cdleary.com/2010/09/picing-on-javascript-for-fun-and-profit/">PICing on JavaScript for fun and profit</a>  for much more about inline caching.</p>
</ul>
<ul>
<em>Register allocation</em><br />
Code generated by basic JITs spends a lot of time reading and writing memory: for code like <code>x+y</code>, the machine code first reads <code>x</code>, then reads <code>y</code>, adds them, and then writes the result to temporary storage. With 64-bit values, that's up to 6 memory accesses. A more advanced JIT, such as J&auml;gerMonkey, generates code that tries to hold most values in registers. J&auml;gerMonkey also does some related optimizations, like trying to avoid storing values at all when they are constant or just a copy of some other value.
</ul>
<p>Here's what J&auml;gerMonkey does to our benchmark scores:<br />
<a href="http://hacks.mozilla.org/2011/03/firefox4-performance/screen-shot-2011-03-14-at-9-27-28-pm/" rel="attachment wp-att-7554"><img src="http://hacks.mozilla.org/wp-content/uploads/2011/03/Screen-shot-2011-03-14-at-9.27.28-PM-250x250.png" alt="" title="Screen shot 2011-03-14 at 9.27.28 PM" width="250" height="250" class="alignnone size-medium wp-image-7554" /></a><br />
That's more than 3x improvement on SunSpider and Kraken and more than 6x on V8!</p>
<p><strong>Fast Graphics: GPU-powered browsing.</strong><br />
For Firefox 4, we sped up how Firefox <a href="http://blog.mozilla.com/joe/2010/05/25/hardware-accelerating-firefox/">draws and composites web pages </a>using the <a href="http://en.wikipedia.org/wiki/GPU">Graphics Processing Unit (GPU) </a> in most modern computers.</p>
<p>On Windows Vista and Windows 7, all web pages are <a href="http://www.basschouten.com/blog1.php/2009/11/22/direct2d-hardware-rendering-a-browser">hardware accelerated using Direct2D </a>. This provides a great speedup for many complex web sites and demo pages.</p>
<p>On Windows and Mac, Firefox uses 3D frameworks (Direct3D or OpenGL) to accelerate the composition of web page elements. This same technique is also used to <a href="http://weblogs.mozillazine.org/roc/archives/2010/12/gpuaccelerated.html">accelerate the display of HTML5 video </a>.</p>
<p><strong>Final take</strong><br />
Fast, hardware-accelerated graphics combined plus fast JavaScript means cutting-edge HTML5 games, demos, and apps run great in Firefox 4. You see it on <a href="http://benfirshman.com/projects/jsnes/">some of the sites</a> <a href="http://people.mozilla.com/~sicking/webgl/ray.html">we enjoyed</a> <a href="http://nerget.com/fluidSim/>enjoyed</a><br />
<a href="http://vis.stanford.edu/protov/ex/force.html">making</a> <a href="https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/sdk/demos/mozilla/spore/index.html">fast</a>. There's plenty more to try in the <a href="https://mozillalabs.com/gaming/">Mozilla Labs Gaming</a> entries and of course, be sure to check out the <a href="https://demos.mozilla.org/">Web O' Wonder</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2011/03/firefox4-performance/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>ECMAScript 5 strict mode in Firefox 4</title>
		<link>http://hacks.mozilla.org/2011/01/ecmascript-5-strict-mode-in-firefox-4/</link>
		<comments>http://hacks.mozilla.org/2011/01/ecmascript-5-strict-mode-in-firefox-4/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 15:37:24 +0000</pubDate>
		<dc:creator>Chris Heilmann</dc:creator>
				<category><![CDATA[Firefox 4]]></category>
		<category><![CDATA[JägerMonkey]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[TraceMonkey]]></category>
		<category><![CDATA[ecmascript]]></category>
		<category><![CDATA[sctrictmode]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=7116</guid>
		<description><![CDATA[Editor&#8217;s note: This article is posted by Chris Heilmann but authored by Jeff Walden &#8211; credit where credit is due. Developers in the Mozilla community have made major improvements to the JavaScript engine in Firefox 4. We have devoted much effort to improving performance, but we&#8217;ve also worked on new features. We have particularly focused [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Editor&#8217;s note</strong>: This article is posted by Chris Heilmann but authored by <a href="http://whereswalden.com">Jeff Walden</a> &#8211; credit where credit is due.</p>
<p>Developers in the Mozilla community have made major improvements to the JavaScript engine in Firefox 4. We have devoted much effort to improving performance, but we&#8217;ve also worked on new features. We have particularly focused on <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript 5</a>, the latest update to the standard underlying JavaScript.</p>
<p>Strict mode is arguably the most interesting new feature in ECMAScript 5. It&#8217;s a way to <em>opt in</em> to a restricted variant of JavaScript. Strict mode isn&#8217;t just a subset: it <em>intentionally</em> has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don&#8217;t rely on strict mode without feature-testing for support for the relevant aspects of strict mode.</p>
<p>Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode blazes a path to future ECMAScript editions where new code with a particular <code>&lt;script type="..."&gt;</code> will likely automatically be executed in strict mode.</p>
<p>What does strict mode do?  First, it eliminates some JavaScript pitfalls that didn&#8217;t cause errors by changing them to produce errors. Second, it fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that&#8217;s not strict mode. Firefox 4 generally hasn&#8217;t optimized strict mode yet, but subsequent versions will. Third, it prohibits some syntax likely to be defined in future versions of ECMAScript.</p>
<h2>Invoking strict mode</h2>
<p>Strict mode applies to <em>entire scripts</em> or to <em>individual functions</em>.  It doesn&#8217;t apply to block statements enclosed in <code>{}</code> braces; attempting to apply it to such contexts does nothing.  <code>eval</code> code, event handler attributes, strings passed to <a href="https://developer.mozilla.org/en/DOM/window.setTimeout"><code>setTimeout</code></a>, and the like are entire scripts, and invoking strict mode in them works as expected.</p>
<h3>Strict mode for scripts</h3>
<p>To invoke strict mode for an entire script, put the <em>exact</em> statement <code>"use strict";</code> (or <code>'use strict';</code>) before any other statements.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Whole-script strict mode syntax</span>
<span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> v <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Hi!  I'm a strict mode script!&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This syntax has a trap that has <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=579119">already bitten</a> <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=627531">a major site</a>: it isn&#8217;t possible to blindly concatenate non-conflicting scripts.  Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict!  The inverse is also true: non-strict plus strict looks non-strict.  Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine.  Only <a href="http://en.wikipedia.org/wiki/Proton_pack">crossing the streams</a> by concatenating strict and non-strict scripts is problematic.</p>
<h3>Strict mode for functions</h3>
<p>Likewise, to invoke strict mode for a function, put the <em>exact</em> statement <code>"use strict";</code> (or <code>'use strict';</code>) in the function&#8217;s body before any other statements.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> strict<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Function-level strict mode syntax</span>
  <span style="color: #3366CC;">'use strict'</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">function</span> nested<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;And so am I!&quot;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;Hi!  I'm a strict mode function!  &quot;</span> <span style="color: #339933;">+</span> nested<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> notStrict<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;I'm not strict.&quot;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Changes in strict mode</h2>
<p>Strict mode changes both syntax and runtime behavior.  Changes generally fall into these categories: </p>
<ul>
<li>Converting mistakes into errors (as syntax errors or at runtime)</li>
<li>Simplifying how the particular variable for a given use of a name is computed</li>
<li>Simplifying <code>eval</code> and <code>arguments</code></li>
<li>Making it easier to write &#8220;secure&#8221; JavaScript</li>
<li>Anticipating future ECMAScript evolution</li>
</ul>
<h3>Converting mistakes into errors</h3>
<p>Strict mode changes some previously-accepted mistakes into errors.  JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics.  Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future.  Strict mode treats these mistakes as errors so that they&#8217;re discovered and promptly fixed.</p>
<p>First, strict mode makes it impossible to accidentally create global variables.  In normal JavaScript, mistyping a variable in an assignment creates a new property on the global object and continues to &#8220;work&#8221; (although future failure is possible: likely, in modern JavaScript).  Assignments which would accidentally create global variables instead throw errors in strict mode:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
mistypedVaraible <span style="color: #339933;">=</span> <span style="color: #CC0000;">17</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a ReferenceError</span></pre></div></div>

<p>Second, strict mode makes assignments which would otherwise silently fail throw an exception.  For example, <code>NaN</code> is a non-writable global variable.  In normal code assigning to <code>NaN</code> does nothing; the developer receives no failure feedback.  In strict mode assigning to <code>NaN</code> throws an exception.  Any assignment that silently fails in normal code will throw errors in strict mode:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
NaN <span style="color: #339933;">=</span> <span style="color: #CC0000;">42</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span>
<span style="color: #003366; font-weight: bold;">var</span> obj <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> get x<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #CC0000;">17</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
obj.<span style="color: #660066;">x</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span>
<span style="color: #003366; font-weight: bold;">var</span> fixed <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
Object.<span style="color: #660066;">preventExtensions</span><span style="color: #009900;">&#40;</span>fixed<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fixed.<span style="color: #660066;">newProp</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;ohai&quot;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span></pre></div></div>

<p>Third, if you attempt to delete undeletable properties, strict mode throws errors (where before the attempt would simply have no effect):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">delete</span> Object.<span style="color: #660066;">prototype</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span></pre></div></div>

<p>Fourth, strict mode requires that all properties named in an object literal be unique.  Normal code may duplicate property names, with the last one determining the property&#8217;s value.  But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance.  Duplicate property names are a syntax error in strict mode:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> o <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> p<span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> p<span style="color: #339933;">:</span> <span style="color: #CC0000;">2</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span></pre></div></div>

<p>Fifth, strict mode requires that function argument names be unique.  In normal code the last duplicated argument hides previous identically-named arguments.  Those previous arguments remain available through <code>arguments[i]</code>, so they&#8217;re not completely inaccessible.  Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> sum<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> a<span style="color: #339933;">,</span> c<span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> a <span style="color: #339933;">+</span> b <span style="color: #339933;">+</span> c<span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// wrong if this code ran</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Sixth, strict mode forbids octal syntax.  Octal syntax isn&#8217;t part of ECMAScript, but it&#8217;s supported in all browsers by prefixing the octal number with a zero: <code>0644 === 420</code> and <code>"\\045" === "%"</code>.  Novice developers sometimes believe a leading zero prefix has no semantic meaning, so they use it as an alignment device &mdash; but this changes the number&#8217;s meaning!  Octal syntax is rarely useful and can be mistakenly used, so strict mode makes octal a syntax error:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> sum <span style="color: #339933;">=</span> 015 <span style="color: #339933;">+</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span>
          <span style="color: #CC0000;">197</span> <span style="color: #339933;">+</span>
          <span style="color: #CC0000;">142</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Simplifying variable uses</h3>
<p>Strict mode simplifies how variable uses map to particular variable definitions in the code.  Many compiler optimizations rely on the ability to say that <em>this</em> variable is stored in <em>this</em> location: this is critical to fully optimizing JavaScript code.  JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform except at runtime.  Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.</p>
<p>First, strict mode prohibits <code>with</code>.  The problem with <code>with</code> is that any name in it might map either to a property of the object passed to it, or to a variable in surrounding code, at runtime: it&#8217;s impossible to know which beforehand.  Strict mode makes <code>with</code> a syntax error, so there&#8217;s no chance for a name in a <code>with</code> to refer to an unknown location at runtime:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">17</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">with</span> <span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// If this weren't strict mode, would this be var x, or</span>
  <span style="color: #006600; font-style: italic;">// would it instead be obj.x?  It's impossible in general</span>
  <span style="color: #006600; font-style: italic;">// to say without running the code, so the name can't be</span>
  <span style="color: #006600; font-style: italic;">// optimized.</span>
  x<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p> The simple alternative of assigning the object to a variable, then accessing the corresponding property on that variable, stands ready to replace <code>with</code>.</p>
<p>Second, <a href="http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/"><code>eval</code> of strict mode code does not introduce new variables into the surrounding code</a>.  In normal code <code>eval("var x;")</code> introduces a variable <code>x</code> into the surrounding function or the global scope.  This means that, in general, in a function containing a call to <code>eval</code>, every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that <code>eval</code> might have introduced a new variable that would hide the outer variable).  In strict mode <code>eval</code> creates variables only for the code being evaluated, so <code>eval</code> can&#8217;t affect whether a name refers to an outer variable or some local variable:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> x <span style="color: #339933;">=</span> <span style="color: #CC0000;">17</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> evalX <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;'use strict'; var x = 42; x&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>x <span style="color: #339933;">===</span> <span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>evalX <span style="color: #339933;">===</span> <span style="color: #CC0000;">42</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Relatedly, if the function <code>eval</code> is invoked by an expression of the form <code>eval(...)</code> in strict mode code, the code will be evaluated as strict mode code.  The code may explicitly invoke strict mode, but it&#8217;s unnecessary to do so.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> strict1<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// str will be treated as strict mode code</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> strict2<span style="color: #009900;">&#40;</span>f<span style="color: #339933;">,</span> str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> f<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// not eval(...): str is strict iff it invokes strict mode</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> nonstrict<span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// str is strict iff it invokes strict mode</span>
<span style="color: #009900;">&#125;</span>
strict1<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;'Strict mode code!'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
strict1<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;'use strict'; 'Strict mode code!'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
strict2<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">eval</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;'Non-strict code.'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
strict2<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">eval</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;'use strict'; 'Strict mode code!'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
nonstrict<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;'Non-strict code.'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
nonstrict<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;'use strict'; 'Strict mode code!'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Third, strict mode forbids deleting plain names.  Thus names in strict mode <code>eval</code> code behave identically to names in strict mode code not being evaluated as the result of <code>eval</code>. Using <code>delete name</code> in strict mode is a syntax error:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;var x; delete x;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span></pre></div></div>

<h3>Making <code>eval</code> and <code>arguments</code> simpler</h3>
<p>Strict mode makes <code>arguments</code> and <code>eval</code> less bizarrely magical.  Both involve a considerable amount of magical behavior in normal code: <code>eval</code> to add or remove bindings and to change binding values, and <code>arguments</code> by its indexed properties aliasing named arguments.  Strict mode makes great strides toward treating <code>eval</code> and <code>arguments</code> as keywords, although full fixes will not come until a future edition of ECMAScript.</p>
<p>First, the names <code>eval</code> and <code>arguments</code> can&#8217;t be bound or assigned in language syntax.  All these attempts to do so are syntax errors:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">eval</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">17</span><span style="color: #339933;">;</span>
arguments<span style="color: #339933;">++;</span>
<span style="color: #339933;">++</span><span style="color: #000066; font-weight: bold;">eval</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> obj <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> set p<span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> x<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> arguments<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">var</span> y <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> f <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #003366; font-weight: bold;">Function</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;arguments&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;'use strict'; return 17;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Second, strict mode code doesn&#8217;t alias properties of <code>arguments</code> objects created within it.  In normal code within a function whose first argument is <code>arg</code>, setting <code>arg</code> also sets <code>arguments[0]</code>, and vice versa (unless no arguments were provided or <code>arguments[0]</code> is deleted). For strict mode functions, <code>arguments</code> objects store the original arguments when the function was invoked. The value of <code>arguments[i]</code> does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding <code>arguments[i]</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> f<span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  a <span style="color: #339933;">=</span> <span style="color: #CC0000;">42</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#91;</span>a<span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">var</span> pair <span style="color: #339933;">=</span> f<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>pair<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">===</span> <span style="color: #CC0000;">42</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>pair<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">===</span> <span style="color: #CC0000;">17</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Third, <code>arguments.callee</code> is no longer supported.  In normal code <code>arguments.callee</code> refers to the enclosing function.  This use case is weak: simply name the enclosing function!  Moreover, <code>arguments.callee</code> substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if <code>arguments.callee</code> is accessed. For strict mode functions, <code>arguments.callee</code>  is a non-deletable property which throws an error when set or retrieved:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> f <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> arguments.<span style="color: #660066;">callee</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span></pre></div></div>

<h3>&#8220;Securing&#8221; JavaScript</h3>
<p>Strict mode makes it easier to write &#8220;secure&#8221; JavaScript.  Some websites now provide ways for users to write JavaScript which will be run by the website <em>on behalf of other users</em>.  JavaScript in browsers can access the user&#8217;s private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality.  JavaScript&#8217;s flexibility makes it effectively impossible to do this without many runtime checks.  Certain language functions are so pervasive that performing runtime checks has considerable performance cost.  A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.</p>
<p>First, the value passed as <code>this</code> to a function in strict mode isn&#8217;t boxed into an object.  For a normal function, <code>this</code> is always an object: the provided object if called with an object-valued <code>this</code>; the value, boxed, if called with a Boolean, string, or number <code>this</code>; or the global object if called with an <code>undefined</code> or <code>null</code> <code>this</code>.  (Use <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply"><code>apply</code></a>, or <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind"><code>bind</code></a> to specify a particular <code>this</code>.)  Automatic boxing is a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality &#8220;secure&#8221; JavaScript environments must invariably.  Thus for a strict mode function, the specified <code>this</code> is used unchanged:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">function</span> fun<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
assert<span style="color: #009900;">&#40;</span>fun<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> undefined<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>fun.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>fun.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>fun.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>undefined<span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> undefined<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
assert<span style="color: #009900;">&#40;</span>fun.<span style="color: #660066;">bind</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>(Tangentially, built-in methods also now won&#8217;t box <code>this</code> if it is <code>null</code> or <code>undefined</code>.  [This change is independent of strict mode but is motivated by the same concern about exposing the global object.]  Historically, passing <code>null</code> or <code>undefined</code> to a built-in method like <code>Array.prototype.sort()</code> would act as if the global object had been specified.  Now passing either value as <code>this</code> to most built-in methods throws a <code>TypeError</code>.  Booleans, numbers, and strings are still boxed by these methods: it&#8217;s only when these methods would otherwise act on the global object that they&#8217;ve been changed.)</p>
<p>Second, in strict mode it&#8217;s no longer possible to &#8220;walk&#8221; the JavaScript stack via commonly-implemented extensions to ECMAScript.  In normal code with these extensions, when a function <code>fun</code> is in the middle of being called, <code>fun.caller</code> is the function that most recently called <code>fun</code>, and <code>fun.arguments</code> is the <code>arguments</code> for that invocation of <code>fun</code>.  Both extensions are problematic for &#8220;secure&#8221; JavaScript, because they allow &#8220;secured&#8221; code to access &#8220;privileged&#8221; functions and their (potentially unsecured) arguments.  If <code>fun</code> is in strict mode, both <code>fun.caller</code> and <code>fun.arguments</code> are non-deletable properties which throw an error when set or retrieved:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> restricted<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  restricted.<span style="color: #660066;">caller</span><span style="color: #339933;">;</span>    <span style="color: #006600; font-style: italic;">// throws a TypeError</span>
  restricted.<span style="color: #660066;">arguments</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> privilegedInvoker<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">return</span> restricted<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
privilegedInvoker<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Third, <code>arguments</code> for strict mode functions no longer provide access to the corresponding function call&#8217;s variables.  In some old ECMAScript implementations <code>arguments.caller</code> was an object whose properties aliased variables in that function.  This is a <a href="http://stuff.mit.edu/iap/2008/facebook/">security hazard</a> because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations.  For these reasons no recent browsers implement it.  Yet because of its historical functionality, <code>arguments.caller</code> for a strict mode function is also a non-deletable property which throws an error when set or retrieved:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">function</span> fun<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> b<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> v <span style="color: #339933;">=</span> <span style="color: #CC0000;">12</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> arguments.<span style="color: #660066;">caller</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// throws a TypeError</span>
<span style="color: #009900;">&#125;</span>
fun<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// doesn't expose v (or a or b)</span></pre></div></div>

<h3>Paving the way for future ECMAScript versions</h3>
<p>Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition.  It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.</p>
<p>First, in strict mode a short list of identifiers become reserved keywords.  These words are <code>implements</code>, <code>interface</code>, <code>let</code>, <code>package</code>, <code>private</code>, <code>protected</code>, <code>public</code>, <code>static</code>, and <code>yield</code>.  In strict mode, then, you can&#8217;t name or use variables or arguments with these names.  A Mozilla-specific caveat: if your code is JavaScript 1.7 or greater (you&#8217;re chrome code, or you&#8217;ve used the right <code>&lt;script type=""&gt;</code>) and is strict mode code, <code>let</code> and <code>yield</code> have the functionality they&#8217;ve had since those keywords were first introduced.  But strict mode code on the web, loaded with <code>&lt;script src=""&gt;</code> or <code>&lt;script&gt;...&lt;/script&gt;</code>, won&#8217;t be able to use <code>let</code>/<code>yield</code> as identifiers.</p>
<p>Second, <a href="http://whereswalden.com/2011/01/24/new-es5-strict-mode-requirement-function-statements-not-at-top-level-of-a-program-or-function-are-prohibited/">strict mode prohibits function statements not at the top level of a script or function</a>.  In normal code in browsers, function statements are permitted &#8220;everywhere&#8221;.  <em>This is not part of ES5!</em>  It&#8217;s an extension with incompatible semantics in different browsers.  Future ECMAScript editions hope to specify new semantics for function statements not at the top level of a script or function.  <a href="http://wiki.ecmascript.org/doku.php?id=conventions:no_non_standard_strict_decls">Prohibiting such function statements in strict mode</a> &#8220;clears the deck&#8221; for specification in a future ECMAScript release:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #3366CC;">&quot;use strict&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">function</span> f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span>
  f<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #CC0000;">5</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">function</span> f2<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #006600; font-style: italic;">// !!! syntax error</span>
  f2<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> baz<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// kosher</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">function</span> eit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #006600; font-style: italic;">// also kosher</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This prohibition isn&#8217;t strict mode proper, because such function statements are an extension.  But it is the recommendation of the ECMAScript committee, and browsers will implement it.</p>
<h2>Strict mode in browsers</h2>
<p>Firefox 4 is the first browser to fully implement strict mode.  The Nitro engine found in many WebKit browsers isn&#8217;t far behind with nearly-complete strict mode support.  Chrome has also <a href="http://codereview.chromium.org/6144005/">started</a> to implement strict mode.  Internet Explorer and Opera haven&#8217;t started to implement strict mode; feel free to send those browser makers feedback requesting strict mode support.</p>
<p>Browsers don&#8217;t reliably implement strict mode, so don&#8217;t blindly depend on it.  <em>Strict mode changes semantics.</em>  Relying on those changes will cause mistakes and errors in browsers which don&#8217;t implement strict mode.  Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant features of strict mode are implemented.</p>
<p>To test out strict mode, download <a href="http://nightly.mozilla.org/">a Firefox nightly</a> and start playing.  Also consider its restrictions when writing new code and when updating existing code.  (To be absolutely safe, however, it&#8217;s probably best to wait to use it in production until it&#8217;s shipped in browsers.)</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2011/01/ecmascript-5-strict-mode-in-firefox-4/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Fun With Fast JavaScript</title>
		<link>http://hacks.mozilla.org/2010/08/fun-with-fast-javascript/</link>
		<comments>http://hacks.mozilla.org/2010/08/fun-with-fast-javascript/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 19:07:47 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[Demo]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JägerMonkey]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[TraceMonkey]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=5509</guid>
		<description><![CDATA[This post is by Vladimir Vukićević and is a re-post from his personal weblog. Fast JavaScript is a cornerstone of the modern web. In the past, application authors had to wait for browser developers to implement any complex functionality in the browser itself, so that they could access it from script code. Today, many of [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post is by Vladimir Vukićević and is a <a href="http://blog.vlad1.com/2010/07/30/fun-with-fast-javascript/">re-post from his personal weblog.</a></em></p>
<p>Fast JavaScript is a cornerstone of the modern web.  In the past, application authors had to wait for browser developers to implement any complex functionality in the browser itself, so that they could access it from script code.  Today, many of those functions can move straight into JavaScript itself.  This has many advantages for application authors: there&#8217;s no need to wait for a new version of a browser before you can develop or ship your app, you can tailor the functionality to exactly what you need, and you can improve it directly (make it faster, higher quality, more precise, etc.).</p>
<p><a href="http://blog.vlad1.com/wp-content/uploads/2010/07/2010-06-24_1353.png" ><img class="alignleft size-full wp-image-316" title="JavaScript Darkroom" src="http://blog.vlad1.com/wp-content/uploads/2010/07/2010-06-24_1353.png" alt="" width="300" height="238" /></a>Here are two examples that show off what can be done with the improved JS engine and capabilities that will be present in Firefox 4.  The first example shows <a href="http://people.mozilla.com/~vladimir/demos/darkroom/darkroom.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/people.mozilla.com');">a simple web-based Darkroom</a><a></a> that allows you to perform color correction on an image.  The HTML+JS is around 700 lines of code, not counting jQuery.  This is based on a demo that&#8217;s included with Google&#8217;s Native Client (NaCl) SDK; in that demo, the color correction work is done inside native code going through NaCl.  That demo (originally presented as &#8220;too slow to run in JavaScript&#8221;) is a few thousand lines of code, and involves downloading and installing platform-specific compilers, multiple steps to test/deploy code, and installing a plugin on the browser side.</p>
<p>I get about 15-16 frames per second with the default zoomed out image (around 5 million pixels per second &#8212; that number won&#8217;t be affected by image size) on my MacBook Pro, which is definitely fast enough for live manipulation.  The algorithm could be tightened up to make this faster still.  Further optimizations to the JS engine could help here as well; for example, I noticed that we spend a lot of time doing floating point to integer conversions for writing the computed pixels back to the display canvas, due to how the canvas API specifies image data handling.</p>
<p>The Web Darkroom tool also supports drag &amp; drop, so you can take any image from your computer and drop it onto the canvas to load it.  A long (long!) time ago, back in 2006, I wrote <a href="http://people.mozilla.com/~vladimir/corppr/" onclick="javascript:pageTracker._trackPageview('/outbound/article/people.mozilla.com');">an addon called &#8220;Croppr!&#8221;</a>.  It was intended to be used with Flickr, allowing users to play around with custom crops of any image, and then leave crop suggestions in comments to be viewed using Croppr.  It almost certainly doesn&#8217;t work any more, but it would be neat to update it: this time with both cropping and color correction.  Someone with the addon (perhaps a <a href="https://jetpack.mozillalabs.com/" onclick="javascript:pageTracker._trackPageview('/outbound/article/jetpack.mozillalabs.com');">Jetpack</a> now!) could then visit a Flickr photo and experiment, and leave suggestions for the photographer.</p>
<p><a href="http://blog.vlad1.com/wp-content/uploads/2010/07/2010-06-24_1352.png" ><img class="alignright size-full wp-image-318" title="JavaScript Video FFT" src="http://blog.vlad1.com/wp-content/uploads/2010/07/2010-06-24_1352.png" alt="" width="350" height="425" /></a>The <a href="http://people.mozilla.com/~vladimir/demos/jsfft/jsfft.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/people.mozilla.com');">second example</a> is based on some work that Dave Humphrey and others have been doing to bring audio manipulation to the web platform.  Originally, their spec included a pre-computed FFT with each audio frame delivered to the web app.  I suggested that there&#8217;s no need for this &#8212; while a FFT is useful for some applications, for others it would be wasted work.  Those apps that want a FFT could implement one in JS.  Some benchmark numbers backed this up &#8212; using the <a href="https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/doc/spec/TypedArray-spec.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/cvs.khronos.org');">typed arrays</a> originally created for <a href="http://webgl.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/webgl.org');">WebGL</a>, computing an FFT in JS was approaching the speed of native code.  Again, both could be sped up (perhaps using SSE2 or something like Mono.Simd on the JS side), but it&#8217;s fast enough to be useful already.</p>
<p>The demo shows this in action.  A numeric benchmark isn&#8217;t really all that interesting, so instead I take a video clip, and as it&#8217;s playing, I extract a portion of the green channel of each frame and compute its 2D FFT, which is then displayed.  The original clip plays at 24 frames per second, so that&#8217;s the upper bound of this demo.  Using Float32 typed arrays, the computation and playback proceeds at around 22-24fps for me.</p>
<p>You can grab the video controls and scrub to a specific frame.  (The frame rate calculation is only correct while the video is playing normally, not while you&#8217;re scrubbing.)  The video source uses Theora, so you&#8217;ll need a browser that can play Theora content.  (I didn&#8217;t have a similar clip that uses WebM, or I could have used that.)</p>
<p>These examples are demonstrating the strength of the trace-based JIT technique that Firefox has used for accelerating JavaScript since Firefox 3.5.  However, not all code can see such dramatic speedups from that type of acceleration.  Because of that, we&#8217;ll be including a full method-based JIT for Firefox 4 (for more details, see <a href="http://www.bailopan.net/blog/?p=683" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.bailopan.net');">David Anderson&#8217;s blog</a>, as well as <a href="http://blog.mozilla.com/dmandelin/2010/05/10/jm-halfway/" onclick="javascript:pageTracker._trackPageview('/outbound/article/blog.mozilla.com');">David Mandelin&#8217;s blog</a>).  This will provide significantly faster baseline JS performance, with the trace JIT becoming a turbocharger for code that it would naturally apply to.</p>
<p>Combining fast JavaScript performance alongside new web platform technologies such as WebGL and Audio will make for some pretty exciting web apps, and I&#8217;m looking forward to seeing what developers do with them!</p>
<p><i>Edit: Made some last-minute changes to the demos, which ended up pulling in a slightly broken version of jQuery UI that wasn&#8217;t all that happy with Safari.  Should be fixed now!</i></p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2010/08/fun-with-fast-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>improving JavaScript performance with JägerMonkey</title>
		<link>http://hacks.mozilla.org/2010/03/improving-javascript-performance-with-jagermonkey/</link>
		<comments>http://hacks.mozilla.org/2010/03/improving-javascript-performance-with-jagermonkey/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 18:42:07 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[Firefox]]></category>
		<category><![CDATA[JägerMonkey]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=4062</guid>
		<description><![CDATA[In August 2008, Mozilla introduced TraceMonkey. The new engine, which we shipped in Firefox 3.5, heralded a new era of performance to build the next generation of web browsers and web applications. Just after the introduction of our new engine Google introduced V8 with Chrome. Apple also introduced their own engine to use in Safari, [...]]]></description>
			<content:encoded><![CDATA[<p>In August 2008, Mozilla introduced <a href="http://weblogs.mozillazine.org/roadmap/archives/2008/08/tracemonkey_javascript_lightsp.html">TraceMonkey</a>.  The new engine, which we shipped in Firefox 3.5, heralded a new era of performance to build the next generation of web browsers and web applications.  Just after the introduction of our new engine Google introduced V8 with Chrome.  Apple also introduced their own engine to use in Safari, and even Opera has a new engine that they&#8217;ve introduced with their latest browser beta.</p>
<p>As a direct result of these new engines we&#8217;ve started to see new types of applications start to emerge.  People experimenting with <a href="http://processingjs.org/">bringing Processing to the web</a>, people experimenting with <a href="http://vocamus.net/dave/?p=974">real-time audio manipulation</a>, <a href="http://benfirshman.com/projects/jsnes/">games</a> and many other things.  (For some good examples have a look at our list of <a href="http://hacks.mozilla.org/category/canvas/">Canvas demos</a>.)</p>
<p>We&#8217;ve learned two things at Mozilla about how our JavaScript engine interacts with these new applications:</p>
<ol>
<li>That the approach that we&#8217;ve taken with tracing tends to interact poorly with certain styles of code.  (That NES game example above, for example, tends to perform very badly in our engine &#8211; it&#8217;s essentially a giant switch statement.)
<li>That when we&#8217;re able to &#8220;stay on trace&#8221; (more on this later) TraceMonkey wins against every other engine.
</ol>
<p>Mozilla&#8217;s engine is fundamentally different than every other engine: everyone else uses what&#8217;s called a &#8220;method-based JIT&#8221;.  That is, they take all incoming JS code, compile it to machine code and then execute it.  Firefox uses a &#8220;tracing JIT.&#8221;  We interpret all incoming JS code and record as we&#8217;re interpreting it.  When we detect a hot path, we turn that into machine code and then execute that inner part.  (For more <a href="http://hacks.mozilla.org/2009/07/tracemonkey-overview/">background on tracing, see this post on hacks from last year</a>.)</p>
<p>The downside of the tracing JIT is that we have to switch back and forth between the interpreter and the machine code whenever we reach certain conditions.  When we have to jump back from machine code to the interpreter this is what we call being &#8220;knocked off trace.&#8221;  The interpreter is, of course, much slower than running native machine code.  And it turns out that happens a lot &#8211; more than anyone expected.</p>
<p>So what we&#8217;re doing in our 2nd generation engine is to combine the best elements of both approaches:</p>
<ol>
<li>We&#8217;re using some chunks of the WebKit JS engine and building a full-method JIT to execute JavaScript code.  This should get us fast baseline JS performance like the other engines.  And most important, it will be consistent &#8211; no more jumping on and off trace and spending a huge amount of time in interpreted code.
<li>We&#8217;ll be bolting our tracing engine into the back of that machine code to generate super-fast code for inner loops.  This means that we&#8217;ll be able to still have the advantages of a tracing engine with the consistency of the method-based JIT.
</ol>
<p>This work is still in the super-early stages, to the point where it&#8217;s not even worth demoing, but we thought it would be worth posting about so people understand the basics of what&#8217;s going on.</p>
<p>You can find more information about this on <a href="http://blog.mozilla.com/dmandelin/2010/02/26/starting-jagermonkey/">David Mandelin</a>&#8216;s and <a href="http://www.bailopan.net/blog/?p=683">David Anderson</a>&#8216;s weblogs as well as the <a href="https://wiki.mozilla.org/JaegerMonkey">project page for the the new engine</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2010/03/improving-javascript-performance-with-jagermonkey/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>JavaScript speedups in Firefox 3.6</title>
		<link>http://hacks.mozilla.org/2010/01/javascript-speedups-in-firefox-3-6/</link>
		<comments>http://hacks.mozilla.org/2010/01/javascript-speedups-in-firefox-3-6/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 17:00:00 +0000</pubDate>
		<dc:creator>Alix Franquet</dc:creator>
				<category><![CDATA[Featured Article]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Firefox 3.6]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=3529</guid>
		<description><![CDATA[This post was written by David Mandelin who works on Mozilla’s JavaScript team. Firefox 3.5 introduced TraceMonkey, our new JavaScript engine that traces loops and JIT compiles them to native (x86/ARM) code. Many JavaScript programs ran 3-4x faster in TraceMonkey compared to Firefox 3. (See our previous article for technical details.) For JavaScript performance in [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post was written by <a href="http://blog.mozilla.com/dmandelin/">David Mandelin</a> who works on Mozilla’s JavaScript team.</em></p>
<p>Firefox 3.5 introduced TraceMonkey, our new JavaScript engine that traces loops and JIT compiles them to native (x86/ARM) code. Many JavaScript programs ran 3-4x faster in TraceMonkey compared to Firefox 3. (See our <a href="http://hacks.mozilla.org/2009/07/tracemonkey-overview/">previous article</a> for technical details.) </p>
<p>For JavaScript performance in Firefox 3.6, we focused on the areas that we thought needed further improvement the most:</p>
<ul>
<li>Some JavaScript code was not trace-compiled in Firefox 3.5. Tracing was disabled by default for Firefox UI JavaScript and add-on JavaScript, so those programs did not benefit from tracing. Also, many advanced JavaScript features were not trace-compiled. For Firefox 3.6, we wanted to trace more programs and more JS features.</li>
<li>Animations coded with JavaScript were often choppy because of garbage collection pauses. We wanted to improve GC performance to make pauses shorter and animations smoother.</li>
</ul>
<p>In this article, I&#8217;ll explain the most important JS performance improvements that come with Firefox 3.6. I&#8217;ll focus on listing what kinds of JS code get faster, including sample programs that show the improvements Fx3.6 makes over Fx3.5. </p>
<h3>JIT for Browser UI JavaScript</h3>
<p>Firefox runs JavaScript code in one of two contexts:<em>content</em> and <em>chrome</em> (no relation to Google Chrome). JavaScript that is part of web content runs in a <em>content</em> context. JavaScript that is part of the browser UI or browser add-ons runs in a <em>chrome</em> context and has extra privileges. For example, chrome JS can alter the main browser UI, but content JS is not allowed to.
</p>
<p>The TraceMonkey JIT can be enabled or disabled separately for content and chrome JS using <code>about:config</code>. Because bugs affecting chrome JS are a greater risk for security and reliability, in Firefox 3.5 we chose to disable the JIT for chrome JS by default. After extensive testing, we&#8217;ve decide to enable the JIT for chrome JS by default, something we did not have time to fully investigate for Fx3.5. Turning on the JIT for chrome should make the JS behind the Firefox UI and add-ons run faster. This difference is probably not very noticeable for general browser usage, because the UI was designed and coded to perform well with the older JS engines. The difference should be more noticeable for add-ons that do heavy JS computation.</p>
<style>
table.ac_table         { margin-left: auto; margin-right: auto }
table.ac_table caption { margin-bottom: 1em }
table.ac_table tr th   { border-bottom: solid 1px black }
table.ac_table th      { border-bottom: solid 1px black }
table.ac_table tr td   { padding-left: 1ex; padding-right: 1ex; text-align: center; font-family: monospace }
table.ac_table tr th   { padding-left: 1ex; padding-right: 1ex; text-align: center }
</style>
<table class='ac_table'>
<tr>
<th>Option
<th>Fx3.5 Default
<th>Fx3.6 Default</tr>
<tr>
<td>javascript.options.jit.chrome
<td>false
<td>true</tr>
<tr>
<td>javascript.options.jit.content
<td>true
<td>true</tr>
<caption><strong><code>about:config</code> options for the JIT</strong></caption>
</table>
<h3>Garbage Collector Performance</h3>
<p>JavaScript is a garbage-collected language, so periodically the JavaScript engine must reclaim unused memory. Our garbage collector (GC) pauses all JavaScript programs while it works. This is fine as long as the pauses are &#8220;short&#8221;. But if the pauses are even a little too long, they can make animations jerky. Animations need to run at 30-60 frames per second to look smooth, which means it should take no longer than 17-33 ms to render one frame. Thus, GC pauses longer than 40 ms cause jerkiness, while pauses under 10 ms should be almost unnoticeable. In Firefox 3.5, pause times were noticeably long, and JavaScript animations are increasingly common on the web, so reducing pause times was a major goal for JavaScript in Firefox 3.6.</p>
<div style='float:left'>
<iframe src='http://demos.hacks.mozilla.org/openweb/extern/clock/clock.html' width='280' height='320' style='border: 3px solid gray; margin-right: 20px;'></iframe></p>
<p style='margin-left: auto; margin-right: auto; text-align: center'>
<strong>Demo: GC Pauses and Animation</strong>
  </p>
</div>
<p><strong>Demo.</strong><br />
The spinning dial animation shown here illustrates pause times. Besides animating the dial, this demo creates one million 100-character strings per second, so it requires frequent GC. The <em>frame delay</em> meter gives the average time between frames in milliseconds. The <em>estimated GC delay</em> meter gives the average estimated GC delay, based on the assumption that if a frame has a delay of 1.7 times the average delay or more, then exactly one GC ran during that frame. (This procedure may not be valid for other browsers, so it is not valid for comparing different browsers. Note also that the GC time also depends on other live JavaScript sessions, so for a direct comparison of two browsers, have the same tabs open in each.) On my machine, I get an estimated GC delay of about 80 ms in Fx3.5, but only 30 ms in Fx3.6.</p>
<p>But it&#8217;s a lot easier to see the difference by opening the demo in Fx3.5, watching it a bit, and then trying it in Fx3.6.<br />
In Fx3.5, I see frequent pauses and the animation looks noticeably jerky. In Fx3.6, it looks pretty smooth, and it&#8217;s hard for me even to tell exactly when the GC is running.
</p>
<p><strong>How Fx3.6 does it better.</strong> We&#8217;ve made many improvements to the garbage collector and memory allocator. I want to give a little more technical details on the big two changes that really cut our pause times.</p>
<p>First, we noticed that a large fraction of the pause time was spent calling <code>free</code> to reclaim the unused memory. We can&#8217;t do much to make freeing memory faster, but we realized we could do it on a separate thread. In Fx3.6, the main JS thread simply adds unused memory chunks to a queue, and another thread frees them during idle time or on a separate processor. This means machines with 2 or more cores will benefit more from this change. But even when one core, freeing might be delayed to an idle time when it will not affect scripts.</p>
<p>Second, we knew that in Fx3.5 running GC clears out all the native code compiled by the JIT as well as some other caches that speed up JS. The reason is that the tracing JIT and GC did not know about each other, so if the GC ran, it might reclaim objects being used by a compiled trace. The result was that immediately after a GC, JS ran a bit slower as the caches and compiled traces were built back up. This would be experienced as either an extended GC pause or a brief hiccup of slow animation right after the GC pause. In Fx3.6, we taught the GC and the JIT to work together, and now the GC does not clear caches or wipe out native code, so it resumes running normally right after GC.</p>
<h3>Tracing More JavaScript Constructs</h3>
<p>In my <a href="http://hacks.mozilla.org/2009/07/tracemonkey-overview/">article on TraceMonkey</a> for the Fx3.5 release, I noted that certain code constructs, such as the <code>arguments</code> object, were not traced and did not get performance improvements from the JIT. A major goal for JS in Fx3.6 was to trace more stuff, so more programs can run faster. We do trace more stuff now, in particular:</p>
<ul>
<li><strong>DOM Properties.</strong> DOM objects are special and harder for the trace compiler to work with. For Fx3.5, we implemented tracing of DOM methods, but not DOM properties. Now we trace DOM properties (and other &#8220;native&#8221; C++ getters and setters) as well. We still do not trace scripted getters and setters.</li>
<li><strong>Closures.</strong> Fx3.5 traced only a few operations involving closures (by which I mean functions that refer to variables defined in lexically enclosing functions). Fx3.6 can trace more programs that use closures. The main operation that is still not traced yet is creating an anonymous function that modifies closure variables. But calling such a function and actually writing to the closure variables are traced.</li>
<li><strong><code>arguments</code>.</strong> We now trace most common uses of the <code>arguments</code> keyword. &#8220;Exotic&#8221; uses, such as setting elements of <code>arguments</code>, are not traced.</li>
<li><strong><code>switch</code>.</strong> We have improved performance when tracing <code>switch</code> statements that use densely packed numeric case labels. These are particularly important for emulators and VMs.</li>
</ul>
<p>These improvements are particularly important for jQuery and Dromaeo, which heavily use <code>arguments</code>, closures, and the DOM. I suspect many other complex JavaScript applications will also benefit. For example, we recently heard from the author that <a href='http://stackulator.com/rtree/'>this R-tree library</a> performs much better in Fx3.6.</p>
<p>Here is a pair of demos of new things we trace. The first sets a DOM property in a loop. The second calls a <strong>sum</strong> function implemented with <code>arguments</code> I get a speedup of about 2x for both of them in Fx3.6 vs. Fx3.5.</p>
<p><script type="text/javascript">
function sum() {
  var ans = 0;
  for (var i = 0; i < arguments.length; ++i)
   ans += arguments[i];
  return ans;
}
function runTracingTests() {
  var t0 = new Date;
  var domObj = document.getElementById('dom_time');
  for (var i = 0; i < 600000; ++i)
    domObj.x = 10;
  var t1 = new Date;
  for (var i = 0; i < 30000; ++i)
    sum(1, 2, 3, 4, 5);
  var t2 = new Date;
  document.getElementById('dom_time').innerHTML = (t1-t0) + ' ms';
  document.getElementById('sum_time').innerHTML = (t2-t1) + ' ms';
}
function showCode(id) {
  var e = document.getElementById(id);
  if (e.style['visibility'] == 'hidden') {
    e.style['visibility'] = 'visible';
    e.style['height'] = 'auto';
  } else {
    e.style['visibility'] = 'hidden';
    e.style['height'] = '0px';
  }
}
</script></p>
<div style='border: 1px solid black; padding: 8px; margin: 12px'>
<p><strong>Demo: Fx3.6 Tracing DOM properties and <code>arguments</code></strong></p>
<p><button onclick='runTracingTests()'>Run</button><br />
  <button onclick='showCode("tracingTestsCode")'>Show/Hide Code</button></p>
<p>DOM Property Set: <strong><span id='dom_time' </span></strong></p>
<p>Sum using <code>arguments</code>: <strong><span id='sum_time'> </span></strong></p>
<pre style='border: 1px solid gray; visibility: hidden; height: 0px' id='tracingTestsCode'>
function sum() {
  var ans = 0;
  for (var i = 0; i < arguments.length; ++i)
    ans += arguments[i];
  return ans;
}

function runTracingTests() {
  var t0 = new Date;

  var domObj = document.getElementById('dom_time');
  for (var i = 0; i < 600000; ++i)
    domObj.x = 10;

  var t1 = new Date;

  for (var i = 0; i < 30000; ++i)
    sum(1, 2, 3, 4, 5);

  var t2 = new Date;

  document.getElementById('dom_time').innerHTML = (t1-t0) + ' ms';
  document.getElementById('sum_time').innerHTML = (t2-t1) + ' ms';
}
</pre>
</div>
<h3>String and RegExp Improvements</h3>
<p>Fx3.6 includes several improvements to string and regular expression performance. For example, the regexp JIT compiler now supports a larger class of regular expressions, including the ever-popular <code>\w+</code>. We also made some of our basic operations faster, like <code>indexOf</code>, <code>match</code>, and <code>search</code>. Finally, we made concatenating sequences of several strings inside a function (a common operation in building up HTML or other kinds of textual output) much faster.</p>
<p style='margin-left: 4ex; margin-right: 4ex'>
<em>Technical aside on how we made string concatenation faster:</em> The C++ function that concatenates two strings S1 and S2 does this: Allocate a buffer big enough to hold the result, then copy the characters of S1 and S2 into the buffer. To concatenate more than two strings, as in JS <code>s + "foo" + t</code>, Fx3.5 simply concatenates two at a time from left to right.</p>
<p style='margin-left: 4ex; margin-right: 4ex'>
Using the Fx3.5 algorithm, to concatenate N strings each of length K, we need to do N-1 memory allocations, and all but one of them are for temporary strings. Worse, the first two input strings are copied N-1 times, the next one is copied N-2 times, and so on. The total number of characters copied is K(N-1)(N+2)/2, which is O(N^2).
</p>
<p style='margin-left: 4ex; margin-right: 4ex'>
Clearly, we can do a lot better. The minimum work we can do is to copy each input string exactly once to the output string, for a total of KN characters copied. Fx3.6 achieves this by detecting sequences of concatenation in JS programs and combining the entire sequence into one operation that uses the optimal algorithm.</p>
<p>Here are a few string benchmarks you can try that are faster in Fx3.6:</p>
<p><script type="text/javascript">
function words() {
  var text_unit = 'word ';
  var text = '';
  for (var i = 0; i < 1000; ++i)
    text += text_unit;
  var t0 = new Date;
  for (var i = 0; i < 300; ++i)
    text.match(/\w+/g)
  return new Date - t0;
}
function indexOf_foo() {
  var text_unit = 'bar baz quux ';
  var text = '';
  for (var i = 0; i < 1000; ++i)
    text += text_unit;
  text += 'foo';
  var t0 = new Date;
  for (var i = 0; i < 3000; ++i)
    text.indexOf('foo')
  return new Date - t0;
}
function match_foo() {
  var text_unit = 'bar baz quux ';
  var text = '';
  //for (var i = 0; i < 1000; ++i)
  //  text += text_unit;
  //text += 'foo';
  text = 'bar baz qux quux foo';
  var t0 = new Date;
  for (var i = 0; i < 100000; ++i)
    text.search('foo')
  return new Date - t0;
}
function runStringTests() {
  var dt1 = words();
  var dt2 = indexOf_foo();
  var dt3 = match_foo();
  var dt4 = buildHTML();
  document.getElementById('words_time').innerHTML = dt1 + ' ms';
  document.getElementById('indexOf_foo_time').innerHTML = dt2 + ' ms';
  document.getElementById('match_foo_time').innerHTML = dt3 + ' ms';
  document.getElementById('buildHTML_time').innerHTML = dt4 + ' ms';
}
function buildHTML(url, text, style) {
  var t0 = new Date;
  for (var i = 0; i < 100000; ++i)
    var q = '<a href="' + url + ' style="' + style + '">' + text + '</a>';
  return new Date - t0;
}
</script></p>
<div style='border: 1px solid black; padding: 8px; margin: 12px'>
<p><strong>Demo: Fx3.6 String Operations</code></strong></p>
<p><button onclick='runStringTests()'>Run</button><br />
  <button onclick='showCode("stringTestsCode")'>Show/Hide Code</button></p>
<p>/\w+/: <strong><span id='words_time'> </span></strong></p>
<p>indexOf('foo'): <strong><span id='indexOf_foo_time'> </span></strong></p>
<p>match('foo'): <strong><span id='match_foo_time'> </span></strong></p>
<p>Build HTML: <strong><span id='buildHTML_time'> </span></strong></p>
<pre style='border: 1px solid gray; visibility: hidden; height: 0px' id='stringTestsCode'>
function words() {
  var text_unit = 'word ';
  var text = '';
  for (var i = 0; i < 1000; ++i)
    text += text_unit;

  var t0 = new Date;
  for (var i = 0; i < 300; ++i)
    text.match(/\w+/g)
  return new Date - t0;
}

function indexOf_foo() {
  var text_unit = 'bar baz quux ';
  var text = '';
  for (var i = 0; i < 1000; ++i)
    text += text_unit;
  text += 'foo';

  var t0 = new Date;
  for (var i = 0; i < 3000; ++i)
    text.indexOf('foo')
  return new Date - t0;
}

function match_foo() {
  var text_unit = 'bar baz quux ';
  var text = '';
  //for (var i = 0; i < 1000; ++i)
  //  text += text_unit;
  //text += 'foo';
  text = 'bar baz qux quux foo';

  var t0 = new Date;
  for (var i = 0; i < 100000; ++i)
    text.search('foo')
  return new Date - t0;
}

function runStringTests() {
  var dt1 = words();
  var dt2 = indexOf_foo();
  var dt3 = match_foo();
  var dt4 = buildHTML();

  document.getElementById('words_time').innerHTML = dt1 + ' ms';
  document.getElementById('indexOf_foo_time').innerHTML = dt2 + ' ms';
  document.getElementById('match_foo_time').innerHTML = dt3 + ' ms';
  document.getElementById('buildHTML_time').innerHTML = dt4 + ' ms';
}

function buildHTML(url, text, style) {
  var t0 = new Date;
  for (var i = 0; i < 100000; ++i)
    var q = '<a href="' + url + ' style="' + style + '">' + text + '</a>';
  return new Date - t0;
}
</pre>
</div>
<h3>Final Thoughts and Next Steps</h3>
<p>We also made a lot of little improvements that don't fit into the big categories above. Most importantly, Adobe, Mozilla, Intel, Sun, and other contributors continue to improve <em>nanojit</em>, the compiler back-end used by TraceMonkey. We have improved its use of memory, made trace recording and compiling faster, and also improved the speed of the generated native code. A better <em>nanojit</em> gives a boost to all JS that runs in the JIT.</p>
<p>There are two big items that didn't make the cut for Fx3.6, but will be in the next version of Firefox and are already available in nightly builds:</p>
<ul>
<li><strong>JITting recursion.</strong> Recursive code, like explicit looping code, is likely to be hot code, so it should be JITted. Nightly builds JIT directly recursive functions. Mutual recursion (g calls f calls g) is not traced yet.</li>
<li><strong>AMD x64 nanojit backend.</strong> Nanojit now has a backend that generates AMD x64 code, which gives the possibility of better performance on that plaform.</li>
</ul>
<p>And if you try a nightly build, you'll find that many of these demos are already even faster than in Fx3.6!</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2010/01/javascript-speedups-in-firefox-3-6/feed/</wfw:commentRss>
		<slash:comments>85</slash:comments>
		</item>
		<item>
		<title>Firefox 3.6 Alpha 1 &#8211; web developer changes</title>
		<link>http://hacks.mozilla.org/2009/08/firefox-36a1-for-developers/</link>
		<comments>http://hacks.mozilla.org/2009/08/firefox-36a1-for-developers/#comments</comments>
		<pubDate>Sat, 08 Aug 2009 02:40:53 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Firefox 3.6]]></category>
		<category><![CDATA[Standards]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=1546</guid>
		<description><![CDATA[As covered on the Mozilla Developer Center, Firefox 3.6 Alpha 1 is now available for download. And we&#8217;ve been busy since Firefox 3.5. Web developers will be interested in a number of features that are new in Firefox 3.6 Alpha 1: The TraceMonkey JavaScript engine has continued to get faster. We&#8217;ve made a huge number [...]]]></description>
			<content:encoded><![CDATA[<p>As covered on the <a href="http://developer.mozilla.org/devnews/">Mozilla Developer Center</a>, <a href="https://developer.mozilla.org/devnews/index.php/2009/08/07/firefox-3-6-alpha-1-now-available-for-download/">Firefox 3.6 Alpha 1 is now available for download</a>.  And we&#8217;ve <a href="https://bugzilla.mozilla.org/buglist.cgi?query_format=advanced&#038;product=Core&#038;product=Firefox&#038;product=NSPR&#038;product=NSS&#038;product=Toolkit&#038;keywords_type=nowords&#038;keywords=fixed1.9.1%2C+verified1.9.1&#038;resolution=FIXED&#038;chfieldfrom=2008-12-01&#038;chfieldto=Now&#038;chfield=resolution&#038;chfieldvalue=FIXED">been busy since Firefox 3.5</a>. </p>
<p>Web developers will be interested in a number of features that are new in Firefox 3.6 Alpha 1:</p>
<ul>
<li>The <a href="http://hacks.mozilla.org/2009/07/tracemonkey-overview/">TraceMonkey JavaScript</a> engine has continued to get faster.
<li>We&#8217;ve made a huge number of improvements to overall DOM and element layout performance.  In some cases we&#8217;re much, much faster.  We&#8217;ll cover details on those in a later post.
<li>The <a href="http://groups.google.com/group/mozilla.dev.platform/browse_thread/thread/e2b791ffc84ee3f4/60c2134a18c2f81a">compositor</a> landing has made it possible to fix a large number of interactions between web content, CSS and plugins.  We&#8217;ll be talking about this in a later post as well.
<li>We now support the <a href="https://developer.mozilla.org/en/CSS/-moz-background-size">-moz-background-size</a> CSS property which lets you set the size of background images.
<li>We now support <a href="https://developer.mozilla.org/en/CSS/Gradients">CSS Gradients</a>.
<li>We now support multiple background images.
<li>We now support the <code>rem</code> unit as a <a href="http://www.w3.org/TR/css3-values/#lengths">CSS unit</a>.
<li><a href="https://developer.mozilla.org/en/CSS/image-rendering">image-rendering</a> is supported for images, background images, videos and canvases.
<li>We now send a <code>reorder</code> event to embedded frames and iframes when their document is loaded.
<li>We&#8217;ve removed the <code>getBoxObjectFor()</code> method.  It was non-standard and exposed all kinds of non-standard stuff to the web.
<li>We now send a <code>hashchange</code> event to a page whenever the URI part after the <code>#</code> changes.
<li>We now have Geolocation <code>address</code> support for user-readable position information.
<li>We now support the <code>complete</code> attribute on <code>document.readystate</code>.
</ul>
<p>You can keep track of this list and other features for XUL and add-ons developers on the <a href="https://developer.mozilla.org/en/Firefox_3.6_for_developers">Firefox 3.6 for developers</a> page on <a href="http://developer.mozilla.org">developer.mozilla.org</a></p>
<p>Unlike the year that passed between Firefox 3 and Firefox 3.5, we expect that this 3.6 release will be released in a small number of months.  Our main focus for the 3.6 release will be end-user perceived performance, TraceMonkey and DOM performance and new web developer features.</p>
<p>Enjoy and test away!</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2009/08/firefox-36a1-for-developers/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		</item>
		<item>
		<title>an overview of TraceMonkey</title>
		<link>http://hacks.mozilla.org/2009/07/tracemonkey-overview/</link>
		<comments>http://hacks.mozilla.org/2009/07/tracemonkey-overview/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 12:28:27 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[35 Days]]></category>
		<category><![CDATA[Feature]]></category>
		<category><![CDATA[Firefox 3.5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=1462</guid>
		<description><![CDATA[This post was written by David Mandelin who works on Mozilla&#8217;s JavaScript team. Firefox 3.5 has a new JavaScript engine, TraceMonkey, that runs many JavaScript programs 3-4x faster than Firefox 3, speeding up existing web apps and enabling new ones. This article gives a peek under the hood at the major parts of TraceMonkey and [...]]]></description>
			<content:encoded><![CDATA[<p><em>This post was written by <a href="http://blog.mozilla.com/dmandelin/">David Mandelin</a> who works on Mozilla&#8217;s JavaScript team.</em></p>
<p>Firefox 3.5 has a new JavaScript engine, TraceMonkey, that runs many JavaScript programs 3-4x faster than Firefox 3, speeding up existing web apps and enabling new ones. This article gives a peek under the hood at the major parts of TraceMonkey and how they speed up JS. This will also explain what kinds of programs get the best speedup from TraceMonkey and what kinds of things you can do to get your program to run faster. </p>
<p><strong>Why it&#8217;s hard to run JS fast: dynamic typing</strong></p>
<p>High-level dynamic languages such as JavaScript and Python make programming more productive, but they have always been slow compared to statically typed languages like Java or C. A typical rule of thumb was that a JS program might be 10x slower than an equivalent Java program.</p>
<p>There are two main reasons JS and other dynamic scripting languages usually run slower than Java or C. The first reason is that in dynamic languages it is generally not possible to determine the types of values ahead of time. Because of this, the language must store all values in a generic format and process values using generic operations.</p>
<p>In Java, by contrast, the programmer declares types for variables and methods, so the compiler can determine the types of values ahead of time. The compiler can then generate code that uses specialized formats and operations that run much faster than generic operations. I will call these <strong>type-specialized</strong> operations.</p>
<p>The second main reason that dynamic languages run slower is that scripting languages are usually implemented with interpreters, while statically typed languages are compiled to native code. Interpreters are easier to create, but they incur extra runtime overhead for tracking their internal state. Languages like Java compile to machine language, which requires almost no state tracking overhead.</p>
<p>Let&#8217;s make this concrete with a picture.  Here are the slowdowns in picture form for a simple numeric add operation: <code>a + b</code>, where <code>a</code> and <code>b</code> are integers. For now, ignore the rightmost bar and focus on the comparison of the Firefox 3 JavaScript interpreter vs. a Java JIT.  Each column shows the steps that have to be done to complete the add operation in each programming language. Time goes downward, and the height of each box is proportional to the time it takes to finish the steps in the box.</p>
<p><a target="_blank" href="http://hacks.mozilla.org/wp-content/uploads/2009/07/complexity.png"><img width="500" src="http://hacks.mozilla.org/wp-content/uploads/2009/07/complexity.png" alt='time diagram of add operation'/></a></p>
<p>In the middle, Java simply runs one machine language add instruction, which runs in time T (one processor cycle). Because the Java compiler knows that the operands are standard machine integers, it can use a standard integer add machine language instruction. That&#8217;s it.</p>
<p>On the left, SpiderMonkey (the JS interpreter in FF3) takes about 40 times as long. The brown boxes are interpreter overhead: the interpreter must read the add operation and jump to the interpreter&#8217;s code for a generic add. The orange boxes represent extra work that has to be done because the interpreter doesn&#8217;t know the operand types. The interpreter has to unpack the generic representations of <code>a</code> and <code>i</code>, figure out their types, select the specific addition operation, convert the values to the right types, and at the end, convert the result back to a generic format.</p>
<p>The diagram shows that using an interpreter instead of a compiler is slowing things down a little bit, but not having type information is slowing things down a lot. If we want JS to run more than a little faster than in FF3, by <a href="http://en.wikipedia.org/wiki/Amdahl%27s_law">Amdahl&#8217;s law</a>, we need to do something about types.</p>
<p><strong>Getting types by tracing</strong></p>
<p>Our goal in TraceMonkey is to compile type-specialized code. To do that, TraceMonkey needs to know the types of variables. But JavaScript doesn&#8217;t have type declarations, and we also said that it&#8217;s practically impossible for a JS engine to figure out the types ahead of time. So if we want to just compile everything ahead of time, we&#8217;re stuck.</p>
<p>So let&#8217;s turn the problem around. If we let the program run for a bit in an interpreter, the engine can directly <em>observe</em> the types of values. Then, the engine can use those types to compile fast type-specialized code. Finally, the engine can start running the type-specialized code, and it will run much faster.</p>
<p>There are a few key details about this idea. First, when the program runs, even if there are many if statements and other branches, the program always goes only one way. So the engine doesn&#8217;t get to observe types for a whole method &mdash; the engine observes types through the paths, which we call <em>traces</em>, that the program actually takes. Thus, while standard compilers compile methods, TraceMonkey compiles traces. One side benefit of trace-at-a-time compilation is that function calls that happen on a trace are inlined, making traced function calls very fast.</p>
<p>Second, compiling type-specialized code takes time. If a piece of code is going to run only one or a few times, which is common with web code, it can easily take more time to compile and run the code than it would take to simply run the code in an interpreter. So it only pays to compile <em>hot code</em> (code that is executed many times). In TraceMonkey, we arrange this by tracing only loops. TraceMonkey initially runs everything in the interpreter, and starts recording traces through a loop once it gets hot (runs more than a few times).</p>
<p>Tracing only hot loops has an important consequence: code that runs only a few times won&#8217;t speed up in TraceMonkey. Note that this usually doesn&#8217;t matter in practice, because code that runs only a few times usually runs too fast to be noticeable. Another consequence is that paths through a loop that are not taken at all never need to be compiled, saving compile time.</p>
<p>Finally, above we said that TraceMonkey figures out the types of values by observing execution, but as we all know, past performance does not guarantee future results: the types might be different the next time the code is run, or the 500th next time. And if we try to run code that was compiled for numbers when the values are actually strings, very bad things will happen. So TraceMonkey must insert type checks into the compiled code. If a check doesn&#8217;t pass, TraceMonkey must leave the current trace and compile a new trace for the new types. This means that code with many branches or type changes tends to run a little slower in TraceMonkey, because it takes time to compile the extra traces and jump from one to another.</p>
<p><strong>TraceMonkey in action</strong></p>
<p>Now, we&#8217;ll show tracing in action by example on this sample program, which adds the first N whole numbers to a starting value:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"> <span style="color: #003366; font-weight: bold;">function</span> addTo<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> n<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
     a <span style="color: #339933;">=</span> a <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>
   <span style="color: #000066; font-weight: bold;">return</span> a<span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #003366; font-weight: bold;">var</span> t0 <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #003366; font-weight: bold;">var</span> n <span style="color: #339933;">=</span> addTo<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">10000000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">print</span><span style="color: #009900;">&#40;</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #000066;">print</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> t0<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>TraceMonkey always starts running the program in the <em>interpreter</em>. Every time the program starts a loop iteration, TraceMonkey briefly enters <em>monitoring</em> mode to increment a counter for that loop. In FF3.5, when the counter reaches 2, the loop is considered hot and it&#8217;s time to trace.</p>
<p>Now TraceMonkey continues running in the interpreter but starts <em>recording</em> a trace as the code runs. The trace is simply the code that runs up to the end of the loop, along with the types used. The types are determined by looking at the actual values. In our example, the loop executes this sequence of JavaScript statements, which becomes our trace:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">    a <span style="color: #339933;">=</span> a <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>    <span style="color: #006600; font-style: italic;">// a is an integer number (0 before, 1 after)</span>
    <span style="color: #339933;">++</span>i<span style="color: #339933;">;</span>          <span style="color: #006600; font-style: italic;">// i is an integer number (1 before, 2 after)</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> n<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// n is an integer number (10000000)</span>
      <span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span></pre></div></div>

<p>That&#8217;s what the trace looks like in a JavaScript-like notation. But TraceMonkey needs more information in order to compile the trace. The real trace looks more like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">  trace_1_start<span style="color: #339933;">:</span>
    <span style="color: #339933;">++</span>i<span style="color: #339933;">;</span>            <span style="color: #666666; font-style: italic;">// i is an integer number (0 before, 1 after)</span>
    temp <span style="color: #339933;">=</span> a <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>   <span style="color: #666666; font-style: italic;">// a is an integer number (1 before, 2 after)</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>lastOperationOverflowed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      exit_trace<span style="color: #009900;">&#40;</span>OVERFLOWED<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    a <span style="color: #339933;">=</span> temp<span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> n<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>   <span style="color: #666666; font-style: italic;">// n is an integer number (10000000)</span>
      exit_trace<span style="color: #009900;">&#40;</span>BRANCHED<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">goto</span> trace_1_start<span style="color: #339933;">;</span></pre></div></div>

<p>This trace represents a loop, and it should be compiled as a loop, so we express that directly using a <code>goto</code>. Also, integer addition can overflow, which requires special handling (for example, redoing with floating-point addition), which in turn requires exiting the trace. So the trace must include an overflow check. Finally, the trace exits in the same way if the loop condition is false. The exit codes tell TraceMonkey why the trace was exited, so that TraceMonkey can decide what to do next (such as whether to redo the add or exit the loop). Note that traces are recorded in a special internal format that is never exposed to the programmer &mdash; the notation used above is just for expository purposes.</p>
<p>After recording, the trace is ready to be <em>compiled</em> to type-specialized machine code.  This compilation is performed by a tiny JIT compiler (named, appropriately enough, <em>nanojit</em>) and the results are stored in memory, ready to be executed by the CPU.</p>
<p>The next time the interpreter passes the loop header, TraceMonkey will start <em>executing</em> the compiled trace. The program now runs very fast.</p>
<p>On iteration 65537, the integer addition will overflow. (2147450880 + 65537 = 2147516417, which is greater than 2^31-1 = 2147483647, the largest signed 32-bit integer.) At this point, the trace exits with an <code>OVERFLOWED</code> code. Seeing this, TraceMonkey will return to interpreter mode and redo the addition. Because the interpreter does everything generically, the addition overflow is handled and everything works as normal. TraceMonkey will also start monitoring this exit point, and if the overflow exit point ever becomes hot, a new trace will be started from that point.</p>
<p>But in this particular program, what happens instead is that the program passes the loop header again. TraceMonkey knows it has a trace for this point, but TraceMonkey also knows it can&#8217;t use that trace because that trace was for integer values, but <code>a</code> is now in a floating-point format. So TraceMonkey records a new trace:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">  trace_2_start<span style="color: #339933;">:</span>
    <span style="color: #339933;">++</span>i<span style="color: #339933;">;</span>            <span style="color: #666666; font-style: italic;">// i is an integer number</span>
    a <span style="color: #339933;">=</span> a <span style="color: #339933;">+</span> i<span style="color: #339933;">;</span>      <span style="color: #666666; font-style: italic;">// a is a floating-point number</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>i <span style="color: #339933;">&lt;</span> n<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>   <span style="color: #666666; font-style: italic;">// n is an integer number (10000000)</span>
      exit_trace<span style="color: #009900;">&#40;</span>BRANCHED<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">goto</span> trace_2_start<span style="color: #339933;">;</span></pre></div></div>

<p>TraceMonkey then compiles the new trace, and on the next loop iteration, starts executing it.  In this way, TraceMonkey keeps the JavaScript running as machine code, even when types change.  Eventually the trace will exit with a BRANCHED code. At this point, TraceMonkey will return to the interpreter, which takes over and finishes running the program.</p>
<p>Here are the run times for this program on my laptop (2.2GHz MacBook Pro):</p>
<table>
<tr>
<td>System</td>
<td>Run Time (ms)</td>
</tr>
<tr>
<td>SpiderMonkey (FF3)</td>
<td>990</td>
</tr>
<tr>
<td>TraceMonkey (FF3.5)</td>
<td>45</td>
</tr>
<tr>
<td>Java (using int)</td>
<td>25</td>
</tr>
<tr>
<td>Java (using double)</td>
<td>74</td>
</tr>
<tr>
<td>C (using int)</td>
<td>5</td>
</tr>
<tr>
<td>C (using double)</td>
<td>15</td>
</tr>
</table>
<p>This program gets a huge 22x speedup from tracing and runs about as fast as Java! Functions that do simple arithmetic inside loops usually get big speedups from tracing. Many of the bit operation and math SunSpider benchmarks, such <code>bitops-3bit-bits-in-byte</code>, <code>ctrypto-sha1</code>, and <code>math-spectral-norm</code> get 6x-22x speedups.</p>
<p>Functions that use more complex operations, such as object manipulation, get a smaller speedup, usually 2-5x. This follows mathematically from Amdahl&#8217;s law and the fact that complex operations take longer. Looking back at the time diagram, consider a more complex operation that takes time 30T for the green part. The orange and brown parts will still be about 30T together, so eliminating them gives a 2x speedup. The SunSpider benchmark <code>string-fasta</code> is an example of this kind of program: most of the time is taken by string operations that have a relatively long time for the green box.</p>
<p>Here is a version of our example program you can try in the browser:</p>
<p><script type="text/javascript">
<!--
function addTo(a, n) {
  for (var i = 0; i < n; ++i)
    a = a + i;
  return a;
}
var dts = 0;
var dtn = 0;
function runExample() {
  var t0 = new Date;
  var n = addTo(0, 10000000);
  var dt = new Date-t0;
  dts += dt;
  dtn += 1;
  var avg = Math.round(dts/dtn);
  document.getElementById('example_result').innerHTML = n + '';
  document.getElementById('example_time').innerHTML = dt + ' ms';
  document.getElementById('example_avg').innerHTML = avg + ' ms';
}
//--></script></p>
<div style='border: 1px solid black; padding: 8px; margin: 12px'>
<button onclick='runExample()'>Run Example</button></p>
<p>Numerical result: <span id='example_result'> </span></p>
<p>Run time: <span id='example_time'> </span></p>
<p>Average run time: <span id='example_avg'> </span></p>
</div>
<p><strong>Understanding and fixing performance problems</strong></p>
<p>Our goal is to make TraceMonkey reliably fast enough that you can write your code in the way that best expresses your ideas, without worrying about performance. If TraceMonkey isn&#8217;t speeding up your program, we hope you&#8217;ll report it as a bug so we can improve the engine. That said, of course, you may need your program to run faster in today&#8217;s FF3.5. In this section, we&#8217;ll explain some tools and techniques for fixing performance of a program that doesn&#8217;t get a good (2x or more) speedup with the tracing JIT enabled. (You can disable the jit by going to <strong>about:config</strong> and setting the pref <strong>javascript.options.jit.content</strong> to <code>false</code>.)</p>
<p>The first step is understanding the cause of the problem. The most common cause is a <em>trace abort</em>, which simply means that TraceMonkey was unable to finish recording a trace, and gave up. The usual result is that the loop containing the abort will run in the interpreter, so you won&#8217;t get a speedup on that loop. Sometimes, one path through the loop is traced, but there is an abort on another path, which will cause TraceMonkey to switch back and forth between interpreting and running native code. This can leave you with a reduced speedup, no speedup, or even a slowdown: switching modes takes time, so rapid switching can lead to poor performance.</p>
<p>With a debug build of the browser or a JS shell (which I <a href="https://developer.mozilla.org/en/Build_Documentation">build</a> myself &#8211; we don&#8217;t publish these builds) you can tell TraceMonkey to print information about aborts by setting the <code>TMFLAGS</code> environment variable. I usually do it like this:</p>
<pre>
TMFLAGS=minimal,abort
dist/MinefieldDebug.app/Contents/MacOS/firefox
</pre>
<p>The <code>minimal</code> option prints out all the points where recording starts and where recording successfully finishes. This gives a basic idea of what the tracer is trying to do. The <code>abort</code> option prints out all the points where recording was aborted due to an unsupported construct. (Setting <code>TMFLAGS=help</code> will print the list of other <code>TMFLAGS</code> options and then exit.)</p>
<p>(Note also that <code>TMFLAGS</code> is the new way to print the debug information. If you are using a debug build of the FF3.5 release, the environment variable setting is <code>TRACEMONKEY=abort</code>.)</p>
<p>Here&#8217;s an example program that doesn&#8217;t get much of a speedup in TraceMonkey.</p>
<p><script type="text/javascript">
<!--
function runExample2() {
  var t0 = new Date;
  var sum = 0;
  for (var i = 0; i < 100000; ++i) {
    sum += i;
  }
  var prod = 1;
  for (var i = 1; i < 100000; ++i) {
    eval("prod *= i");
  }
  var dt = new Date - t0;
  document.getElementById('example2_time').innerHTML = dt + ' ms';
}
//--></script></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> runExample2<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> t0 <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> sum <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    sum <span style="color: #339933;">+=</span> i<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> prod <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;prod *= i&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #003366; font-weight: bold;">var</span> dt <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date <span style="color: #339933;">-</span> t0<span style="color: #339933;">;</span>
  document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span>example2_time<span style="color: #3366CC;">').innerHTML = dt + '</span> ms<span style="color: #3366CC;">';
}</span></pre></div></div>

<div style='border: 1px solid black; padding: 8px; margin: 12px'>
<button onclick='runExample2();' style='margin-right:32px'>Run Example 2</button><br />
Run time: <span id='example2_time'> </span>
</div>
<p>If we set <code>TMFLAGS=minimal,abort</code>, we&#8217;ll get this:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Recording starting from ab.js:5@23
recording completed at  ab.js:5@23 via closeLoop
&nbsp;
Recording starting from ab.js:5@23
recording completed at  ab.js:5@23 via closeLoop
&nbsp;
Recording starting from ab.js:10@63
Abort recording of tree ab.js:10@63 at ab.js:11@70: eval.
&nbsp;
Recording starting from ab.js:10@63
Abort recording of tree ab.js:10@63 at ab.js:11@70: eval.
&nbsp;
Recording starting from ab.js:10@63
Abort recording of tree ab.js:10@63 at ab.js:11@70: eval.</pre></div></div>

<p>The first two pairs of lines show that the first loop, starting at line 5, traced fine. The following lines showed that TraceMonkey started tracing the loop on line 10, but failed each time because of an <code>eval</code>.</p>
<p>An important note about this debug output is that you will typically see some messages referring to <em>inner trees</em> growing, stabilizing, and so on. These really aren&#8217;t problems: they usually just indicate a <em>delay</em> in finishing tracing a loop because of the way TraceMonkey links inner and outer loops. And in fact, if you look further down the output after such aborts, you will usually see that the loops eventually do trace.</p>
<p>Otherwise, aborts are mainly caused by JavaScript constructs that are not yet supported by tracing. The trace recording process is easier to implement for a basic operation like <code>+</code> than it is for an advanced feature like <code>arguments</code>. We didn&#8217;t have time to do robust, secure tracing of every last JavaScript feature in time for the FF3.5 release, so some of the more advanced ones, like <code>arguments</code>, aren&#8217;t traced in FF3.5.0. Other advanced features that are not traced include getters and setters, with, and eval. There is partial support for closures, depending on exactly how they are used. Refactoring to avoid these constructs can help performance.</p>
<p>Two particularly important JavaScript features that are not traced are:</p>
<ul>
<li>Recursion. TraceMonkey doesn&#8217;t see repetition that occurs through recursion as a loop, so it doesn&#8217;t try to trace it. Refactoring to use explicit <code>for</code> or <code>while</code> loops will generally give better performance.
<li>Getting or setting a DOM property. (DOM method calls are fine.) Avoiding these constructs is generally impossible, but refactoring the code to move DOM property access out of hot loops and performance-critical segments should help.
</ul>
<p>We are actively working on tracing all the features named above. For example, support for tracing <code>arguments</code> is already available in nightly builds.</p>
<p>Here is the slow example program refactored to avoid <code>eval</code>. Of course, I could have simply done the multiplication inline. Instead, I used a function created by <code>eval</code> because that&#8217;s a more general way of refactoring an <code>eval</code>. Note that the <code>eval</code> still can&#8217;t be traced, but it only runs once so it doesn&#8217;t matter.</p>
<p><script type="text/javascript">
<!--
function runExample3() {
  var t0 = new Date;
  var sum = 0;
  for (var i = 0; i < 100000; ++i) {
    sum += i;
  }
  var prod = 1;
  var mul = eval("(function(i) { return prod * i; })");
  for (var i = 1; i < 100000; ++i) {
    prod = mul(i);
  }
  var dt = new Date - t0;
  document.getElementById('example3_time').innerHTML = dt + ' ms';
}
//--></script></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> runExample3<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> t0 <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> sum <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    sum <span style="color: #339933;">+=</span> i<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> prod <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> mul <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;(function(i) { return prod * i; })&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    prod <span style="color: #339933;">=</span> mul<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #003366; font-weight: bold;">var</span> dt <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date <span style="color: #339933;">-</span> t0<span style="color: #339933;">;</span>
  document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'example3_time'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span> <span style="color: #339933;">=</span> dt <span style="color: #339933;">+</span> <span style="color: #3366CC;">' ms'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<div style='border: 1px solid black; padding: 8px; margin: 12px'>
<button onclick='runExample3();' style='margin-right:32px'>Run Example 3</button><br />
Run time: <span id='example3_time'> </span>
</div>
<p>There are a few more esoteric situations that can also hurt tracing performance. One of them is <em>trace explosion</em>, which happens when a loop has many paths through it. Consider a loop with 10 <code>if</code> statements in a row: the loop has 1024 paths, potentially causing 1024 traces to be recorded. That would use up too much memory, so TraceMonkey caps each loop at 32 traces. If the loop has fewer than 32 hot traces, it will perform well. But if each path occurs with equal frequency, then only 3% of the paths are traced, and performance will suffer.</p>
<p>This kind of problem is best analyzed with <a href='https://developer.mozilla.org/en/TraceVis'<strong>TraceVis</strong></a>, which creates visualizations of TraceMonkey performance. Currently, the build system only supports enabling TraceVis for shell builds, but the basic system can also run in the browser, and there is <a href='https://bugzilla.mozilla.org/show_bug.cgi?id=497999'>ongoing work</a> to enable TraceVis in a convenient form in the browser.</p>
<p>The <a href='http://blog.mozilla.com/dmandelin/2009/02/26/tracevis-performance-visualization-for-tracemonkey/'>blog post</a> on TraceVis is currently the most detailed explanation of what the diagrams mean and how to use them to diagnose performance problems. The post also contains a detailed analysis of a diagram that is helpful in understanding how TraceMonkey works in general.</p>
<p><strong>Comparative JITerature</strong></p>
<p>Here I will give a few comparisons to other JavaScript JIT designs. I&#8217;ll focus more on hypothetical designs than competing engines, because I don&#8217;t know details about them &mdash; I&#8217;ve read the release information and skimmed a few bits of code. Another big caveat is that real-world performance depends at least as much on engineering details as it does on engine architecture.</p>
<p>One design option could be a called a <em>per-method non-specializing JIT</em>. By this, I mean a JIT compiler that compiles a method at a time and generates generic code, just like what the interpreter does. Thus, the brown boxes from our diagrams are cut out. This kind of JIT doesn&#8217;t need to take time to record and compile traces, but it also does not type-specialize, so the orange boxes remain. Such an engine can still be made pretty fast by carefully designing and optimizing the orange box code. But the orange box can&#8217;t be completely eliminated in this design, so the maximum performance on numeric programs won&#8217;t be as good as a type-specializing engine.</p>
<p>As far as I can tell, as of this writing Nitro and V8 are both lightweight non-specializing JITs. (I&#8217;m told that V8 does try to guess a few types by looking at the source code (such as guessing that <code>a</code> is an integer in <code>a >> 2</code>) in order to do a bit of type specialization.) It seem that TraceMonkey is generally faster on numeric benchmarks, as predicted above. But TraceMonkey suffers a bit on benchmarks that use more objects, because our object operations and memory management haven&#8217;t been optimized as heavily.</p>
<p>A further development of the basic JIT is the <em>per-method type-specializing JIT</em>. This kind of a JIT tries to type-specialize a method based on the argument types the method is called with. Like TraceMonkey, this requires some runtime observation: the basic design checks the argument types each time a method is called, and if those types have not been seen before, compiles a new version of the method. Also like TraceMonkey, this design can heavily specialize code and remove both the brown and orange boxes.</p>
<p>I&#8217;m not aware that anyone has deployed a per-method type-specializing JIT for JavaScript, but I wouldn&#8217;t be surprised if people are working on it.</p>
<p>The main disadvantage of a per-method type-specializing JIT compared to a tracing JIT is that the basic per-method JIT only directly observes the input types to a method. It must try to infer types for variables inside the method algorithmically, which is difficult for JavaScript, especially if the method reads object properties. Thus, I would expect that a per-method type-specializing JIT would have to use generic operations for some parts of the method. The main advantage of the per-method design is that the method needs to be compiled exactly once per set of input types, so it&#8217;s not vulnerable to trace explosion. In turn, I think a per-method JIT would tend to be faster on methods that have many paths, and a tracing JIT would tend to be faster on highly type-specializable methods, especially if the method also reads a lot of values from properties.</p>
<p><strong>Conclusion</strong></p>
<p>By now, hopefully you have a good idea of what makes JavaScript engines fast, how TraceMonkey works, and how to analyze and fix some performance issues that may occur running JavaScript under TraceMonkey. Please report bugs if you run into any significant performance problems. Bug reports are also a good place for us to give additional tuning advice. Finally, we&#8217;re trying to improve constantly, so check out nightly TraceMonkey builds if you&#8217;re into the bleeding edge.</p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2009/07/tracemonkey-overview/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
		<item>
		<title>connecting html5 video to the web</title>
		<link>http://hacks.mozilla.org/2009/06/connecting-html5-video/</link>
		<comments>http://hacks.mozilla.org/2009/06/connecting-html5-video/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 06:20:00 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[35 Days]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Firefox 3.5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TraceMonkey]]></category>
		<category><![CDATA[Video]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=738</guid>
		<description><![CDATA[This is a screencast of a demo that I gave at the open video conference in NYC on June 19th, 2009. The demo itself was created by the ever wonderful Paul Rouget. Download .ogv or .mp4 version. A version hosted on blip.tv.]]></description>
			<content:encoded><![CDATA[<p><em>This is a screencast of a demo that I gave at the <a href="http://openvideoconference.org/">open video conference</a> in NYC on June 19th, 2009.  The demo itself was created by the ever wonderful <a href="http://blog.mozbox.org">Paul Rouget</a>.<br />
</em></p>
<div>
<video width="500" controls><source src="http://videos.mozilla.org/serv/blizzard/35days/face-detection/face-off-480.ogv" type="video/ogg"/><source src="http://videos.mozilla.org/serv/blizzard/35days/face-detection/face-off-480.mp4" type="video/mp4"/><embed src="http://blip.tv/play/AYGLhG2U8hw" type="application/x-shockwave-flash" width="500" height="394" allowscriptaccess="always" allowfullscreen="true"></embed></video>
</div>
<div>
Download <a href="http://videos.mozilla.org/serv/blizzard/35days/face-detection/face-off-480.ogv">.ogv</a> or <a href="http://videos.mozilla.org/serv/blizzard/35days/face-detection/face-off-480.mp4">.mp4</a> version.  A <a href="http://blip.tv/file/2265515">version hosted on blip.tv</a>.
</div>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2009/06/connecting-html5-video/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
<enclosure url="http://videos.mozilla.org/serv/blizzard/35days/face-detection/face-off-480.ogv" length="7893997" type="video/ogg" />
		</item>
		<item>
		<title>what does tracemonkey feel like?</title>
		<link>http://hacks.mozilla.org/2009/06/tracemonkey-demo/</link>
		<comments>http://hacks.mozilla.org/2009/06/tracemonkey-demo/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 04:03:42 +0000</pubDate>
		<dc:creator>Christopher Blizzard</dc:creator>
				<category><![CDATA[35 Days]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[Firefox 3.5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[TraceMonkey]]></category>

		<guid isPermaLink="false">http://hacks.mozilla.org/?p=271</guid>
		<description><![CDATA[One of our goals with Firefox 3.5 is to help upgrade the web. Over the lifecycle of this release we&#8217;ve invested heavily in developer features. One of the features that we&#8217;ve invested in is TraceMonkey &#8211; a tracing interpreter that turns commonly-run JavaScript code into machine code so that it can run at near-native speeds. [...]]]></description>
			<content:encoded><![CDATA[<p>One of our goals with Firefox 3.5 is to help upgrade the web.  Over the lifecycle of this release we&#8217;ve invested heavily in developer features.  One of the features that we&#8217;ve invested in is TraceMonkey &#8211; a tracing interpreter that turns commonly-run JavaScript code into machine code so that it can run at near-native speeds.  We consider it to be both an end user feature because it makes existing web applications faster as well as a developer feature because of the new kinds of applications it enables.</p>
<p>We&#8217;re always challenged to try and come up with ways to describe what that means in a way that&#8217;s not a dry benchmark.  How can we explain what it <em>feels</em> like?</p>
<p>We&#8217;ve made a video to help describe both what it means by the numbers, but also shows what it feels like.  If you want to <a href="http://people.mozilla.com/~schrep/image12.html">try the demo</a> we suggest you try it in both Firefox 3 and Firefox 3.5.  It&#8217;s something you can really feel.</p>
<p><video width="500" controls><source src="http://videos.mozilla.org/serv/blizzard/35days/tracemonkey-perf/ff_blizzard_2ndDraft.ogv" type="video/ogg"/><source src="http://videos.mozilla.org/serv/blizzard/35days/tracemonkey-perf/ff_blizzard_2ndDraft.mp4" type="video/mp4"/>
<div style="text-align: center; background-color: #EEE; color: #F00; padding: 10px; margin: 10px; border: solid; border-width: 2px">Sadfaces.  Your browser doesn&#8217;t support native video. Maybe you can try the <a href="http://videos.mozilla.org/serv/blizzard/35days/tracemonkey-perf/ff_blizzard_2ndDraft.ogv">.ogv</a> version or the <a href="http://videos.mozilla.org/serv/blizzard/35days/tracemonkey-perf/ff_blizzard_2ndDraft.mp4">.mp4</a> version and hope for the best?</div>
<p></video></p>
]]></content:encoded>
			<wfw:commentRss>http://hacks.mozilla.org/2009/06/tracemonkey-demo/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
<enclosure url="http://videos.mozilla.org/serv/blizzard/35days/tracemonkey-perf/ff_blizzard_2ndDraft.ogv" length="11206497" type="video/ogg" />
		</item>
	</channel>
</rss>

