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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With