user332336
user332336

Reputation: 91

Javascript: Why does the maximum stack size appear to change dynamically?

When I run the function below, I get different results on different browsers:

function maxCallStackSize0() {
    try {
        return 1 + maxCallStackSize0();
    } catch (e) {
        return 1;
    }
}
maxCallStackSize0(); // Opera: 32354, Chrome: 12795

But that's not all. The result also changes if I run it manually multiple times:

maxCallStackSize0(); // Opera: 34724
maxCallStackSize0(); // Opera: 33776
maxCallStackSize0(); // Opera: 34030

Is that because of other functions being called in the background taking up some of the stack?

I have also seen that the more arguments I pass, the smaller the call stack:

function maxCallStackSize3(s1, s2, s3, s4) {
    try {
        return 1 + maxCallStackSize3(s1, s2, s3, s4);
    } catch (e) {
        return 1;
    }
}
maxCallStackSize3("hello", "how", "are", "you"); // Opera: 13979, Chrome: 6971

Is that because the parameters are part of the call stack, and the more/the bigger size parameters I pass, the shorter the call stack can be before it overflows?

Is it possible to know the maximum size of the call stack in bytes?

Thanks

Upvotes: 0

Views: 56

Answers (1)

user3637541
user3637541

Reputation: 693

The stack size depends on multiple things here.

Firstly, when you call a function, all the parameters and a return address are pushed to the stack. Also all local variables that you would define within the function would be on the stack.

Secondly, the stack grows in the opposite direction as the heap. A process uses one memory space for the stack and the heap. If you have variables on the heap (for example if you instantiate a variable with new it will be created on the heap, not on the stack). The more on the heap, the less room there is for the stack to grow into.

I don't know how your setup looks like, but if there is anything else running in your browser-tab than that will interfere with the stack-size as it will take up some space.

Upvotes: 1

Related Questions