简体   繁体   中英

Javascript memory management in functions

Example code below;

function a() {
    var a = 123;
    //some stuff
    b();
}

function b() {
    //some stuff
}

a();

So my question is whether the variable 'a' is in memory while b() is executed ?

Thank you.

Yes it is. It's not in b() 's scope, but it is in memory.

You can't just magically delete objects withing a() 's scope. You could manually delete a; if you wouldn't need it anymore, but the best and most reasonable way to do this is by calling them one after the other instead of nested calls:

function a() {
    var a = 123;
    //some stuff
}

function b() {
    //some stuff
}

a();
b();

If there is not a quick way to do this, consider refactoring your code a bit

This is going to be both implementation specific, and program specific. It will depend on the exact javascript platform it is running on, things like the system memory size, and how much code/how many variables were allocated before a() was run.

You can't rely on it being deallocated before or during b() , because garbage collection is non-deterministic.

In most cases, it will probably stay in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM