<p>I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? </p>

<pre><code>for (var i = 0; i &lt; 1000; ++i) {
    myObjects[i].onMyEvent = function() {
        // do something
    };
}
</code></pre>

<p>vs</p>

<pre><code>function myEventHandler() {
    // do something
}

for (var i = 0; i &lt; 1000; ++i) {
    myObjects[i].onMyEvent = myEventHandler;
}
</code></pre>

<p>The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?</p>

[{'answer_id': 80823, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 2, 'selected': False, 'text': "<p>As a general design principle, you should avoid implimenting the same code multiple times. Instead you should lift common code out into a function and execute that (general, well tested, easy to modify) function from multiple places.</p>\n\n<p>If (unlike what you infer from your question) you are declaring the internal function once and using that code once (and have nothing else identical in your program) then an anonomous function <em>probably</em> (thats a guess folks) gets treated the same way by the compiler as a normal named function.</p>\n\n<p>Its a very useful feature in specific instances, but shouldn't be used in many situations.</p>\n"}, {'answer_id': 80840, 'author': 'Joe Skora', 'author_id': 14057, 'author_profile': 'https://Stackoverflow.com/users/14057', 'pm_score': 1, 'selected': False, 'text': "<p>I wouldn't expect much difference but if there is one it will likely vary by scripting engine or browser.  </p>\n\n<p>If you find the code easier to grok, performance is a non-issue unless you expect to call the function millions of times.</p>\n"}, {'answer_id': 80882, 'author': 'Sarhanis', 'author_id': 7966, 'author_profile': 'https://Stackoverflow.com/users/7966', 'pm_score': 0, 'selected': False, 'text': "<p>What will definitely make your loop faster across a variety of browsers, especially IE browsers, is looping as follows:</p>\n\n<pre><code>for (var i = 0, iLength = imgs.length; i &lt; iLength; i++)\n{\n   // do something\n}\n</code></pre>\n\n<p>You've put in an arbitrary 1000 into the loop condition, but you get my drift if you wanted to go through all the items in the array.</p>\n"}, {'answer_id': 80927, 'author': 'nickf', 'author_id': 9021, 'author_profile': 'https://Stackoverflow.com/users/9021', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s my test code:</p>\n\n<pre><code>var dummyVar;\nfunction test1() {\n    for (var i = 0; i &lt; 1000000; ++i) {\n        dummyVar = myFunc;\n    }\n}\n\nfunction test2() {\n    for (var i = 0; i &lt; 1000000; ++i) {\n        dummyVar = function() {\n            var x = 0;\n            x++;\n        };\n    }\n}\n\nfunction myFunc() {\n    var x = 0;\n    x++;\n}\n\ndocument.onclick = function() {\n    var start = new Date();\n    test1();\n    var mid = new Date();\n    test2();\n    var end = new Date();\n    alert ("Test 1: " + (mid - start) + "\\n Test 2: " + (end - mid));\n}\n</code></pre>\n\n<p>The results:<br>\nTest 1: 142ms\nTest 2: 1983ms</p>\n\n<p>It appears that the JS engine doesn\'t recognise that it\'s the same function in Test2 and compiles it each time.</p>\n'}, {'answer_id': 81185, 'author': 'annakata', 'author_id': 13018, 'author_profile': 'https://Stackoverflow.com/users/13018', 'pm_score': 0, 'selected': False, 'text': '<p>@nickf</p>\n\n<p>That\'s a rather fatuous test though, you\'re comparing the execution <em>and compilation</em> time there which is obviously going to cost method 1 (compiles N times, JS engine depending) with method 2 (compiles once). I can\'t imagine a JS developer who would pass their probation writing code in such a manner.</p>\n\n<p>A far more realistic approach is the anonymous assignment, as in fact you\'re using for your document.onclick method is more like the following, which in fact mildly favours the anon method.</p>\n\n<p>Using a similar test framework to yours:</p>\n\n<hr>\n\n<pre><code>function test(m)\n{\n    for (var i = 0; i &lt; 1000000; ++i) \n    {\n        m();\n    }\n}\n\nfunction named() {var x = 0; x++;}\n\nvar test1 = named;\n\nvar test2 = function() {var x = 0; x++;}\n\ndocument.onclick = function() {\n    var start = new Date();\n    test(test1);\n    var mid = new Date();\n    test(test2);\n    var end = new Date();\n    alert ("Test 1: " + (mid - start) + "ms\\n Test 2: " + (end - mid) + "ms");\n}\n</code></pre>\n'}, {'answer_id': 81329, 'author': 'Atif Aziz', 'author_id': 6682, 'author_profile': 'https://Stackoverflow.com/users/6682', 'pm_score': 8, 'selected': True, 'text': '<p>The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function:</p>\n\n<pre><code>for (var i = 0; i &lt; 1000; ++i) {    \n    myObjects[i].onMyEvent = function() {\n        // do something    \n    };\n}\n</code></pre>\n\n<p>You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope (<a href="http://www.google.com/search?q=javascript+closure" rel="noreferrer">closure</a>). The following seems faster, on the other hand, because it simply assigns the <em>same</em> function reference to the array elements throughout the loop:</p>\n\n<pre><code>function myEventHandler() {\n    // do something\n}\n\nfor (var i = 0; i &lt; 1000; ++i) {\n    myObjects[i].onMyEvent = myEventHandler;\n}\n</code></pre>\n\n<p>If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version:</p>\n\n<pre><code>var handler = function() {\n    // do something    \n};\nfor (var i = 0; i &lt; 1000; ++i) {    \n    myObjects[i].onMyEvent = handler;\n}\n</code></pre>\n\n<p>In short, there is no observable performance cost to using anonymous over named functions.</p>\n\n<p>As an aside, it may appear from above that there is no difference between:</p>\n\n<pre><code>function myEventHandler() { /* ... */ }\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>var myEventHandler = function() { /* ... */ }\n</code></pre>\n\n<p>The former is a <em>function declaration</em> whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “<a href="http://www.dustindiaz.com/javascript-function-declaration-ambiguity/" rel="noreferrer">JavaScript function declaration ambiguity</a>”.</p>\n\n<p>The actual execution time for any approach is largely going to be dictated by the browser\'s implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit <a href="http://jsperf.com/named-or-anonymous-functions/12" rel="noreferrer">the JS Perf site</a></p>\n'}, {'answer_id': 81354, 'author': 'matt lohkamp', 'author_id': 14026, 'author_profile': 'https://Stackoverflow.com/users/14026', 'pm_score': 0, 'selected': False, 'text': "<p>a reference is nearly always going to be slower then the thing it's refering to. Think of it this way - let's say you want to print the result of adding 1 + 1. Which makes more sense:</p>\n\n<pre><code>alert(1 + 1);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>a = 1;\nb = 1;\nalert(a + b);\n</code></pre>\n\n<p>I realize that's a really simplistic way to look at it, but it's illustrative, right? Use a reference only if it's going to be used multiple times - for instance, which of these examples makes more sense:</p>\n\n<pre><code>$(a.button1).click(function(){alert('you clicked ' + this);});\n$(a.button2).click(function(){alert('you clicked ' + this);});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function buttonClickHandler(){alert('you clicked ' + this);}\n$(a.button1).click(buttonClickHandler);\n$(a.button2).click(buttonClickHandler);\n</code></pre>\n\n<p>The second one is better practice, even if it's got more lines. Hopefully all this is helpful. (and the jquery syntax didn't throw anyone off)</p>\n"}, {'answer_id': 81481, 'author': 'Christopher Tokar', 'author_id': 315650, 'author_profile': 'https://Stackoverflow.com/users/315650', 'pm_score': 0, 'selected': False, 'text': '<p>YES! Anonymous functions are faster than regular functions. Perhaps if speed is of the utmost importance... more important than code re-use then consider using anonymous functions.</p>\n\n<p>There is a really good article about optimizing javascript and anonymous functions here:</p>\n\n<p><a href="http://dev.opera.com/articles/view/efficient-javascript/?page=2" rel="nofollow noreferrer">http://dev.opera.com/articles/view/efficient-javascript/?page=2</a></p>\n'}, {'answer_id': 81726, 'author': 'annakata', 'author_id': 13018, 'author_profile': 'https://Stackoverflow.com/users/13018', 'pm_score': 0, 'selected': False, 'text': '<p>@nickf</p>\n\n<p>(wish I had the rep to just comment, but I\'ve only just found this site)</p>\n\n<p>My point is that there is confusion here between named/anonymous functions and the use case of executing + compiling in an iteration. As I illustrated, the difference between anon+named is negligible in itself - I\'m saying it\'s the use case which is faulty.</p>\n\n<p>It seems obvious to me, but if not I think the best advice is "don\'t do dumb things" (of which the constant block shifting + object creation of this use case is one) and if you aren\'t sure, test!</p>\n'}, {'answer_id': 83689, 'author': 'pcorcoran', 'author_id': 15992, 'author_profile': 'https://Stackoverflow.com/users/15992', 'pm_score': -1, 'selected': False, 'text': "<p>Anonymous objects are faster than named objects.  But calling more functions is more expensive, and to a degree which eclipses any savings you might get from using anonymous functions.  Each function called adds to the call stack, which introduces a small but non-trivial amount of overhead.</p>\n\n<p>But unless you're writing encryption/decryption routines or something similarly sensitive to performance, as many others have noted it's always better to optimize for elegant, easy-to-read code over fast code.</p>\n\n<p>Assuming you are writing well-architected code, then issues of speed should be the responsibility of those writing the interpreters/compilers.</p>\n"}, {'answer_id': 33904169, 'author': 'Pablo Estornut', 'author_id': 4433714, 'author_profile': 'https://Stackoverflow.com/users/4433714', 'pm_score': 1, 'selected': False, 'text': '<p>Where we can have a performance impact is in the operation of declaring functions. Here is a benchmark of declaring functions inside the context of another function or outside:</p>\n\n<p><a href="http://jsperf.com/function-context-benchmark" rel="nofollow">http://jsperf.com/function-context-benchmark</a></p>\n\n<p>In Chrome the operation is faster if we declare the function outside, but in Firefox it\'s the opposite.</p>\n\n<p>In other example we see that if the inner function is not a pure function, it will have a lack of performance also in Firefox:\n<a href="http://jsperf.com/function-context-benchmark-3" rel="nofollow">http://jsperf.com/function-context-benchmark-3</a></p>\n'}, {'answer_id': 44602865, 'author': 'bluenote10', 'author_id': 1804173, 'author_profile': 'https://Stackoverflow.com/users/1804173', 'pm_score': 0, 'selected': False, 'text': '<p>As pointed out in the comments to @nickf answer: The answer to </p>\n\n<blockquote>\n  <p>Is creating a function once faster than creating it a million times</p>\n</blockquote>\n\n<p>is simply yes. But as his JS perf shows, it is not slower by a factor of a million, showing that it actually gets faster over time.</p>\n\n<p>The more interesting question to me is:</p>\n\n<blockquote>\n  <p>How does a repeated <strong>create + run</strong> compare to create once + repeated <strong>run</strong>.</p>\n</blockquote>\n\n<p>If a function performs a complex computation the time to create the function object is most likely negligible. But what about the over head of <strong>create</strong> in cases where <strong>run</strong> is fast? For instance:</p>\n\n\n\n<pre><code>// Variant 1: create once\nfunction adder(a, b) {\n  return a + b;\n}\nfor (var i = 0; i &lt; 100000; ++i) {\n  var x = adder(412, 123);\n}\n\n// Variant 2: repeated creation via function statement\nfor (var i = 0; i &lt; 100000; ++i) {\n  function adder(a, b) {\n    return a + b;\n  }\n  var x = adder(412, 123);\n}\n\n// Variant 3: repeated creation via function expression\nfor (var i = 0; i &lt; 100000; ++i) {\n  var x = (function(a, b) { return a + b; })(412, 123);\n}\n</code></pre>\n\n<p>This <a href="https://jsperf.com/function-creation-performance-overhead/1" rel="nofollow noreferrer">JS Perf</a> shows that creating the function just once is faster as expected. However, even with a very quick operation like a simple add, the overhead of creating the function repeatedly is only a few percent.</p>\n\n<p>The difference probably only becomes significant in cases where creating the function object is complex, while maintaining a negligible run time, e.g., if the entire function body is wrapped into an <code>if (unlikelyCondition) { ... }</code>.</p>\n'}]
['https://Stackoverflow.com/questions/80802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9021/']