2

Possible Duplicate:
How is the memory allocation done for variables in scripting languages?

In javascript, since it is a loosely typed language, when I write the code:

var foo;

Exactly after this step how many blocks of memory is allocated. I din assign anything to it and also when I type

var foo = 10;

and

var foo = "this is random"

in both cases how many bytes of memory is allocated?

Community
  • 1
  • 1
Bhagirath N Sai
  • 199
  • 4
  • 16
  • dup of http://stackoverflow.com/questions/582134/how-is-the-memory-allocation-done-for-variables-in-scripting-languages? – Senthil Kumar Aug 19 '12 at 18:42

1 Answers1

1

I'm not sure about the specifics, which are implementation dependent, but here's what I'd guess.

Simply doing var foo; doesn't create any new objects. However, foo might need to be added to a dictionary of declared variables in which case space for the string foo and possible metadata is allocated, assuming it isn't interned.

When you do var foo = 10; or var foo = "this is random" it creates string or integer variables respectively, which would normally take up memory. However small ints and constant strings are almost certainly interned. Plus the JIT might optimize away the number reference to a plain machine integer, which case it doesn't take any extra memory at all.

Anyway, it's hard to say much specific about performance in a high level language with varying implementations, especially when a JIT is involved.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • can u elaborate on what u said on the JIT might optimize away the number reference to a plain machine integer, which case it doesn't take any extra memory at all – Bhagirath N Sai Aug 19 '12 at 19:02
  • A plain machine int is at most as big as a pointer on most architectures. So not only is no new object being created, it doesn't even take any extra memory. – Antimony Aug 19 '12 at 19:22