I have 2 node js programs.
console.log('TEST A:');
function computeMaxCallStackSizeA() {
try {
return 1 + computeMaxCallStackSizeA();
} catch (e) {
return 1;
}
}
for (let i = 0; i < 5; i++)
console.log(computeMaxCallStackSizeA());
console.log('\nTEST B:');
function computeMaxCallStackSizeB() {
try {
let a = [];
for(let i=0;i<100;i++) a.push('1234567890');
return 1 + computeMaxCallStackSizeB();
} catch (e) {
return 1;
}
}
for (let i = 0; i < 5; i++)
console.log(computeMaxCallStackSizeB());
- The first program's result is 12559.
- The second program's result is 13870.
- Why does the second program use more memory but still has a larger call stack maximum size?
UPDATE:
- If we change the program as follow:
function computeMaxCallStackSizeC() {
try {
let a1 = '11111111111111111111111111111111111111111111111111111';
let a2 = '22222222222222222222222222222222222222222222222222222';
let a3 = '33333333333333333333333333333333333333333333333333333';
let a4 = '44444444444444444444444444444444444444444444444444444';
let a5 = '55555555555555555555555555555555555555555555555555555';
let a6 = '66666666666666666666666666666666666666666666666666666';
return 1 + computeMaxCallStackSizeC();
} catch (e) {
return 1;
}
}
for (let i = 0; i < 5; i++)
console.log(computeMaxCallStackSizeC());
The maximum recursion depth is decreased. Because Stack memory is used to store local variables (such as a number, a string) and heap memory is used to store the data of dynamically allocated pointer (such as an array). Is that right?