stack size and callbacks in javascript
Do async operations with callbacks increase the stack size? I don't have enough knowledge of javascript interpreters or the proper tools to figure this out. My goto t开发者_运维问答ool is the firebug console and it shows that the stack size is not increasing but I could be looking at it wrong. So does anyone know?
An asynchronous callback, just like an event callback, is run one-by-one through the event loop. It is not called from the same call stack of the function that put it in the event loop, as each function in the loop is run to completion before the next is called. So no, they don't increase the stack size.
I believe all javascript engines in modern browsers are single threaded, which means the callback cannot actually occur until the current execution path has ended. This will mean that the stack has unwound completely and the callback will occur with (essentially) a new stack.
The stack size will only increase when you call a function or declare a local variable. The stack will decrease in size again when you leave the scope that caused the increase.
If you are more interested in overall memory usage, then it's a little more complicated.
Callbacks will take up a bit of memory until they are executed but the javascript engine should clean up after itself once the callback has finished. If you put new data on the heap (via global variables, for example) then that memory will not be freed because it will still be in use after the callback.
精彩评论