The performance problem here is the cost of creating a new functional object at each iteration of the loop, and not the fact that you are using an anonymous function:
for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() {
You create a thousand different function objects, although they have the same code and are not attached to the lexical area ( closure ). On the other hand, it looks faster, because it just assigns the same function to reference the elements of the array during the loop:
function myEventHandler() {
If you were to create an anonymous function before entering the loop, then only assign it references to array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever compared to the named version of the function
var handler = function() {
In short, there is no observable operational cost of using anonymous over named functions.
Aside, it may seem from above that there is no difference between:
function myEventHandler() { }
and
var myEventHandler = function() { }
The first is a function declaration, and the second is the assignment of a variable to an anonymous function. Although they may have the same effect, JavaScript handles them a little differently. To understand the difference, I recommend reading the " ambiguity of declaring JavaScript functions .
The actual runtime for any approach will be largely determined by the implementation of the compiler browser and runtime. For a complete comparison of current browser performance, visit the JS Perf website
Atif Aziz Sep 17 '08 at 9:07 2008-09-17 09:07
source share