Ryan Chan said:
I knwe function in JS can be written like below to avoid function name
collision, e.g.
(function(i, j) {
alert(i + j);
}) (1, 2);
However, beside avoiding function name collision, are there any other
benefits / drawbacks, e.g.
memory usage, speed?
Memory usage:
Maybe. It's possible that the code for the body of the function can
be garbage collected after it has been run, while the top level code for
a script element might be retained ... unless the code for the script
element will be GC'ed too.
By avoiding global variable names, it's likely that some data might be
GC'ed after the function has returned that would otherwise be retained
... unless you null or delete the variables manually.
Speed:
Mayble. You create a function object and call it, so that's a slight
overhead. Inside the function, local variable lookup might be faster
than global variable lookup (for several reasons), but if you do need
global variable lookup inside the function, some implementations might
be marginally slower (but a good optimizing implementation should be
able to determine whether a lookup is global and not need to traverse
the scope chain at runtime).
In any case, the code is likely to be run only once, so unless it
contains a big loop, performance is not going to be measurable.
The big win is maintainance. Avoiding putting variables into the
global object makes collisions less likely (and possibly other
global object lookups marginally faster).
/L