23

In other words, what options do I have to allocate memory in JavaScript?

I know you can allocate memory either globally, or inside function scope. Can I allocate memory dynamically? What does the new operator really mean?

Edit: here's a specific example. How would you implement reading an integer value from the user - n, and then read n integers into an array?

nicael
  • 18,550
  • 13
  • 57
  • 90
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • For the "specific example": just `.push()` the values in. `const n = read()` then `const arr = []; for (let i = 0; i < n; i += 1) { arr.push(read()) }`. "Arrays" in JS are "Vectors" in memory-conscious languages. – Félix Saparelli Oct 14 '15 at 04:01
  • For people looking at this question later: In the case of a language like JS, heap and stack are not inherent to the language and can be quite implementation-dependent. V8 has the separation of heap and stack, and `null`, `undefined`, `true` and `false`, though primitive, are actually allocated on the heap. This answer http://stackoverflow.com/a/6604390/1460448 has more details. For a normal JS programmer though this is more like implementation details only. – xji Feb 26 '17 at 00:01

7 Answers7

24

you can't allocate memory. you can create objects. that's what new does.

now, javascript is a queer creature: functions are also objects in javascript. So this mean that you can instantiate prettymuch everything using new.

So, the new operator means that a new object is being created.

Javascript also garbage-collects these variables, just like it happens in java. So if you know java, it should be easy for you to draw parallels.

cheers,

jrh

PS: when you allocate objects, you really are allocating memory. Only, you are not doing that explicitly. You can allocate an array, and make it behave like a memory buffer, but that will degrade javascript performance drastically: javascript arrays are not in-memory buffers, they are also objects (like everything else).

jrharshath
  • 25,975
  • 33
  • 97
  • 127
7

JavaScript has garbage collection and handles this for you.

However, you can help it by using the delete operator where appropriate.

From the Apple JavaScript Coding Guidelines:

Just as you used the new operator to create an object, you should delete objects when you are finished with them, like this:

delete myObjectVariable;

The JavaScript runtime automatically garbage collects objects when their value is set to null. However, setting an object to null doesn’t remove the variable that references the object from memory. Using delete ensures that this memory is reclaimed in addition to the memory used by the object itself. (It is also easier to see places where your allocations and deallocations are unbalanced if you explicitly call delete.)

Steve

Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • 1
    I just read an article which said that's a bad idea: "In quite a few discussions online about reclaiming memory in JavaScript, the delete keyword is brought up, as although it was supposed to be used for just removing keys from a map, some developers think you can force de-referencing using it. Avoid using delete if you can." For more details, go to http://goo.gl/2Abpe9 DE-REFERENCING MISCONCEPTIONS section – gtournie Oct 08 '14 at 08:30
5

Hmmm sounds to me like you are coming from the memory focused language and trying to shoe horn that logic into JS. Yes JS uses memory (of course), but we have garbage collection to take care of cleaning it all up.

If you are after specifics about the guts of memory allocation then you will have to hunt around for that. But as a rule thumb, when you use var, new or declaring a new function (or closure) you are gobbling up memory. You can get vars to null to flag them for garbage collection and you can use the delete keyword too although few do either of these unless they work Server-side (like myself with ASP JScript) where its important.

Pete Duncanson
  • 3,208
  • 2
  • 25
  • 35
4

Javascript is really, really friendly — really, too friendly by half!

If you have an array of 3 elements, and you want to add a fourth, you can just act as if that array location already exists:

    var arr = ['zero', 'one', 'two'];
    // Now you have arr[0], arr[1] and arr[2].
    // arr.length is equal to 3.
.
    // to add arr[8]:
    arr[8] = 'eight';
    // Now you have arr[0] through arr[8]. arr.length is equal to 9.
    // and arr[3] through arr[7] exist, and 
    // are initialized to undefined. (If I remember right.)

So being really specific with memory allocation is unnecessary when adding elelments.

Brian Wren
  • 367
  • 5
  • 15
3

No, you don’t need to and can’t allocate memory. The JavaScript interpreter does that automatically.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • I can't agree with that statement. var i = 0 is memory allocation for all I'm concerned. If I'm not allocating memory, I'm not programming. – Yuval Adam Jun 22 '09 at 10:46
  • 1
    So you rather want to know what the `var` is for and why it should be used? – Gumbo Jun 22 '09 at 11:04
  • 1
    The connotation of "memory allocation" is to specify the number of bytes you want, allocate them (receiving a way to refer to the allocated memory), then store stuff there. Since JScript handles all that for you, the term "memory allocation" is not a good name choice for what transpires. – Brian Wren Apr 03 '14 at 14:23
2

To answer the title of the question, if you are to trust in MDN, most JavaScript implementations have a heap:

Heap

Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.

Several Runtimes Communicating Together

A web worker or a cross-origin iframe has its own stack, heap, and message queue. Two distinct runtimes can only communicate through sending messages via the postMessage method. This method adds a message to the other runtime if the latter listens to message events.

For a deeper dive into memory management, there is also an article here although much of this is implementation specific.

Community
  • 1
  • 1
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
0

You do not need to manually manage memory in Javascript. Both heap and stacks are used under the hood to manage memory and it depends on the implementation. Usually, local variables are on the stack and objects are on the heap.