简体   繁体   中英

Memory allocation using “new” in Javascript

I have few basic questions about dynamic object creation using Javascript. I understand that browser takes care of allocating memory space for any 'new' keyword found in the JS. If my understanding is correct, then i have following queries one by one.

Query #1 : Please refer the comments given below for the two lines inside 'sample' function. That is my first query.

function sample() {
  var a = 5;      // is the memory allocated for variable 'a' in stack ?
  var b = new obj1(); // The object instance created for 'obj1' gets allocated in heap?
}

var obj1 = function() {
  this.strDate = "";
}

Query #2: Once the execution scope is out of function sample(), will the browser engine free the memory allocated for both the variables. I have read about GC's reference algorithm & mark and sweep algorithm and recommendations to assign null to variables once not in use, yet could not get a clear cut idea on the standards to be followed as we would do in C++. If variable a is there in stack, then I need not worry and if obj1 instance is no longer accessible or say unmarked or no further reference to it, will it also be cleared by GC ?.

Query #3: Do browsers differ in allocating and freeing memory for the instances created using 'new' operator. ( I had seen only about heap profilers in chrome and rather few more terms related to it, but I have also come across 'out of stack space' error. Does that mean all browsers would universally use both stack and heap ?

Please help me out here ;)

  1. As a programmer, in JavaScript you do not have control over stack or heap allocation. You create objects or primitives that are located somewhere in the memory. Internally JS engines (such as V8 or Spidermonkey) perform all kinds of optimizations. Generally you can think of everything as if it's stored on heap.
  2. To get started you need to know that GC frees the memory from the objects that are not referenced. While you hold a reference to an object somewhere in your code, it will not be destroyed.
  3. Browsers (JS engines) do not leak memory allocation abstraction to you. The error you're referring to is probably call stack exceeded that happens when too many functions are called (mostly due to recursion).

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