Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For example, in javascript

I can say

var x = 5;

Later I can do

x = 'a';

and then

x = "hello";

So, how is memory allocated for the variables? As it is, all variables have a common type 'var' and values of variables can change at run-time as seen above. Isn't it a difficult task to allocate and manage memory for these variables? Exactly, how is it done?

like image 335
Real Red. Avatar asked Feb 24 '09 15:02

Real Red.


1 Answers

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.

like image 91
unwind Avatar answered Oct 23 '22 11:10

unwind