简体   繁体   中英

Uninitialized variable memory allocation

JavaScript Example :

Suppose I do this:

var i;

And never use i anywhere else in the program. Will it be allocated any memory?

Or if I use, say i=2; after some lines.... will it be allocated memory at this point, or is the memory allocated during the creation of i?

C# example :

Suppose I do this:

dynamic i;

And never use i anywhere else in the program. Will it be allocated any memory (and if it will be, when? During compilation?)?

Or if I use, say i=2; after some lines.... will it be allocated memory at this point, or is the memory allocated during the creation of i, or is it allocated during compilation?

Also, would there be any other differences regarding memory allocation in the two examples above except the differences that arise due to the fact that JavaScript is an interpreted language and C# is a compiled language?

In C#, the expression:

var i;

can't be compiled in the first place; if we consider instead:

int i; // or dynamic i;

then that can be compiled and may or may not be retained, but it depends on whether it is a field (object variable) versus a local (method variable). Fields are not removed; however, the compiler is free to remove local variables as it sees fit. Whether it chooses to do so can depend on a lot of things, but most notably: whether you are doing an optimized release build, versus a debug build. Even if a local variable is clearly both written and read, the compiler can still remove it if it chooses - of course, the value will still exist on the stack, but not in a reserved location.

When the Javascript interpreter parses var i; and then executes the containing scope, it has to store the fact somewhere that the i variable is now defined in the current scope. Futures references in this scope will access this particular variable in this scope. Though implementation details are left to the implementor, the variable i is likely added to a particular scope object and thus has to consume some memory.

It is possible that if the variable is not referenced and it is in a contained scope without the use of things like eval() that the JS engine may be able to optimize it away. Whether or not it actually thinks it can do that and actually does so would have to be discovered by testing or studying of the source code.

Individual variables like this would likely consume only very small amounts of memory. For this to be of major consequence, you would likely have to have thousands of these.

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