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

前端 未结 2 1635
有刺的猬
有刺的猬 2020-12-20 20:12

For example, in javascript

I can say

var x = 5;

Later I can do

x = \'a\';

and then



        
相关标签:
2条回答
  • 2020-12-20 20:27

    Python uses a technique called reference counting, which basically puts a counter in the value. Each time a reference to a value is created, the counter is incremented. When a reference to the value is lost (for instance when you assign a new value to 'x'), the value is decremented. When the counter reaches zero, that means that no reference to the value exists, and it can be deallocated. This is a simplified explanation, but that's at least the basics.

    0 讨论(0)
  • 2020-12-20 20:30

    Well, those variables are references to immutable strings which are allocated at compile time.

    Of course it depends on the VM, but in general, I think, most C-based scripting languages allocate a large block of memory, expanding it as necessary and do their own allocation within that, rarely if ever giving anything back to the O/S. Especially in a lexically scoped language, which almost all of them are, variables are all allocated dynamically within this block, not on anything analogous to a C stack, and they are freed with either reference counting or with a garbage collector.

    If your scripting language is running on the JVM, or .NET, or something like it (Parrot?), creating a variable is merely the creation of something like a Java object. Some time after there are no more references to the object, the garbage collector will reclaim the memory.

    0 讨论(0)
提交回复
热议问题