Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript recursive stack overflow

Is there anybody would explain why the result is different below?

// test one
function computeMaxCallStackSize() {
    try {
        return computeMaxCallStackSize() + 1;
    } catch (e) {
        return 1;
    }
}

console.log(computeMaxCallStackSize()); 

result is 17958

// test two
    function computeMaxCallStackSize() {
        try {
            return 1 + computeMaxCallStackSize();
        } catch (e) {
            return 1;
        }
    }

    console.log(computeMaxCallStackSize());

result is 15714

When the position of the function 'computeMaxCallStackSize' is different,the result is different too. What's the reason? Thanks very much!

Running environment: node.js v6.9.1 OS:Win7

like image 745
myzhou Avatar asked Oct 29 '22 09:10

myzhou


1 Answers

Its not the position but the order of execution which leads to this in the first function the statement

 return computeMaxCallStackSize() + 1;

calls the increment first and then adds 1

return 1 + computeMaxCallStackSize();

If you try both return statements as same then it leads to same value. In later one as digit is first the js call stack exceeds overflow sooner as compared to first. The callstack value depends on the order of execution as in 2nd you change the order you get a lower value as recursion happens later.

You can also check by adding some console.log() or local variable call stack will decrease gradually with increase in execution statements.

If you try computeMaxCallStackSize() + 1; in both you will get same value.

like image 193
Vinod Louis Avatar answered Nov 15 '22 04:11

Vinod Louis