Within instances of objects I like to use the closure mechanism to simulate private member variables. For a potential large number of created objects I don't need some of the private members though, but I have to declare them for them to be used in the closure, like "one", "two" and "three" here:
var obj=function()
{
var one;
var two;
var three;
var M=function()
{
one=5;
};
};
(Don't mind that this is not actually a working example of my setup, it's just to demonstrate the use of the closure over the three vars with M.)
Do the var statements themselves already consume memory, or does that depend on actually assigning something to these vars like with "one"?
Each boolean and number variable takes 8 bytes of memory.
If you declare a variable, without using "var", the variable always becomes GLOBAL.
This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.
Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.
The interpreter has to store information about scope - one = 5
will change the local variable one
instead of creating a global variable (which would happen with e.g. four = 5
). This information must cost some memory somehow. This memory usage also applies before assigning a value to one
, because the information has to be available at the time you're assigning.
How much memory it will cost is difficult to say since it differs per interpreter. I guess it isn't enough to worry about.
Note that two
/three
are not used at all and may be garbage collected in this example. (Actually, you don't expose M
either, so everything may be garbage collected right away in this example.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With