On 13/09/2012, at 08:00, Maxim Kazantsev wrote:
> It is a pretty typical approach to use an anonymous function for asynchronous
> calls from inside a loop:
>
> var a = getInitialData();
> for (var i = 0, len = a.length; i < len; i++) {
> (function(el) {
> /* do something non-blocking here */
> })(a[i]);
> }
>
> JSLint doesn't like this code with "Don't make functions within a loop"
> warning, and it is actually right since it really creates a new anonymous
> function on every single loop iteration. An obvious solution is to declare
> this function outside a loop, but it would make a code less readable.
Come on!
> Even if a declaration would just precede the loop: you see a call here, you
> see a declaration somewhere else, and here you are, lost all your attention.
Perhaps. Or perhaps not. If you give the inner function a good name it will
help understand what's going on there.
> My question is how bad this approach is for an overall performance?
Well, even though this:
function ƒ (i) { ctr+= i }
while (i--) ƒ(i);
is twice as fast as this:
while (i--) (function (i) { ctr+= i })(i);
<https://gist.github.com/3714498>
$ node test.js
(function (i) { ctr+= i })(i) -> 39.74ns
ƒ(i) -> 18.99ns
the difference is tiny, only 20 nano seconds!
> In particular, how fast and efficient a garbage collection of anonymous
> functions is? How much memory a typical anonymous function can consume and
> how long it may exist in a memory?
I wouldn't bother too much about these things either. Simply follow Crock's
advice and declare ƒ outside of the loop. Or don't, it should just work in any
case.
--
Jorge.
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en