0

I have a recursive call in node.js. I am trying to figure how to optimize it so it uses the lease CPU cycles and has the smallest stack memory.

function baz(callback) {

        if (bool){
            callback();
            return;
        }
        else{
            setImmediate(function(){
                return baz(callback);
            });
        }
}

The only thing I can really tweak is the presence of return statements and where to place them. I think the stack will grow more without returning in the right place.

Is there a profiling tool for node.js where I can see the stack during runtime?

1

1 Answer 1

1

By placing your call to baz inside setImmediate you aren't actually recursing down a call stack in the way you might think. The key point to realize is that your first call to baz will return before your second call to baz begins. (Note that in javascript functions the return keyword is optional, a function simply returns undefined by default once it reaches the end of the function block)

Or, think of it this way. Some event, call it event A, triggers the first call to baz and the beginning of your recursive routine. The callback you give to setImmediate will not start right away, it will be queued as a new event, call it event 'B', and this event won't start until after event A has finished, after execution has climbed back out of that event's call stack.

Node.js will continue resolivng any other events that might have been scheduled in priority before your setImmediate was called, until it eventually gets to event 'B' and runs your second invocation of baz, and so on.

In other words, baz is an event driven algorithm, not a recursive one. Your stack depth won't grow arbitrarily large.

Sign up to request clarification or add additional context in comments.

1 Comment

Whether bool is true or false, the return statement inside your setImmediate callback is returning undefined. It's worth noting that node will simply ignore this return value. Edit: Oops, you deleted the question I was responding to :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.