Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is defining JS prototype functions separately faster than in a dictionary?
    text
    copied!<p>This may seem like a particularly obscure point, however I am attempting to improve my grounding in the Javascript language as a whole (more specifically its best and most efficient practices).</p> <p>Whilst testing a theory in <a href="http://jsperf.com/" rel="nofollow">http://jsperf.com/</a> I came up with some odd results:</p> <p>Suppose we have two "identical" prototypes, defined as follows:</p> <p><strong>Object1</strong></p> <pre><code>var Object1 = function() {} Object1.prototype.defaults = { radius: 400, up: 1 } Object1.prototype.centerOffset = function() { return this.defaults.radius*this.defaults.up; } </code></pre> <p><strong>Object2</strong></p> <pre><code>var Object2 = function() {} Object2.prototype = { defaults: { radius: 400, up: 1 }, centerOffset: function() { return this.defaults.radius*this.defaults.up; } } </code></pre> <p><strong>Object1</strong> has a consistent (if marginal: ~3%) speed advantage over <strong>Object2</strong> when performing the following simple operations:</p> <pre><code>var o = new Object1(); var offset = o.centerOffset(); </code></pre> <p>&amp; </p> <pre><code>var o = new Object2(); var offset = o.centerOffset(); </code></pre> <p>You can run the tests yourself <a href="http://jsperf.com/correct-way-to-declare-prototype-functions" rel="nofollow">here</a>. I am using Chrome 25 on OSX 10.6.8.</p> <p>What I would like to know is this:</p> <ul> <li>What is the reason(s) for this performance difference?</li> <li>Is this performance indicative of some best practice in javascript?</li> </ul> <p>Thanks in advance guys.</p> <p>EDIT: Thanks for the responses - as some have mentioned, further testing on my part seems to suggest that this issue is browser (or rather, Javascript compiler specific). I've tested additionally in Safari, IE 10 and Firefox. IE 10 and Firefox both gave results so close as to be no different. Safari executed the operations on Object2 slightly faster than those on Object1 (around 2% on average). I would like to know what the outlier (Other) is though, as the performance difference in that case appears to be substantial.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload