Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs decrease v8 garbage collector memory usage

I'm debugging a nodejs application with util module and while heapUsed value stays around 30-100MB, heapTotal value grows up to 1.4GB.

Here is a question about similar behaviour

I've read that this is the way how v8 garbage collector behaves, but the question is how to decrease the amount of memory it allocates (make it less than 1.4GB) if running on 512 MB device for example

like image 839
Herokiller Avatar asked May 15 '15 06:05

Herokiller


People also ask

What is the default V8 memory limit on 32-bit system?

Currently, by default V8 has a memory limit of 512mb on 32-bit systems, and 1gb on 64-bit systems. The limit can be raised by setting --max-old-space-size to a maximum of ~1gb (32-bit) and ~1.7gb (64-bit), but it is recommended that you split your single process into several workers if you are hitting memory limits.

How do you prevent memory leaks in Node js?

Avoid Accidental Globals This could be the result of a typo and could lead to a memory leak. Another way could be when assigning a variable to this within a function in the global scope. To avoid issues like this, always write JavaScript in strict mode using the 'use strict'; annotation at the top of your JS file.

How much RAM does Nodejs need?

At least 2GB of RAM. At least 4 vCPUs.


Video Answer


1 Answers

You need to control the max memory size flags (all sizes are taken in MB).

The recommended amounts for a "low memory device" are:

node --max-executable-size=96 --max-old-space-size=128 --max-semi-space-size=1 app.js

for 32-bit and/or Android and

node --max-executable-size=192 --max-old-space-size=256 --max-semi-space-size=2 app.js

for 64-bit non-android.

These would limit the heap totals to 225mb and 450mb respectively. It doesn't include memory usage outside JS. For instance buffers are allocated as "c memory" , not in the JavaScript heap.

Also you should know that the closer you are to the heap limit the more time is wasted in GC. E.g. if you are at 95% memory usage 90% of the CPU would be used for GC and 10% for running actual code (not real numbers but give the general idea). So you should be as generous as possible with the limits and never exceed say 16% of the maximum memory usage (I.E. heapUsed/limit should not be greater than 0.16). 16% is just something I recall from some paper, it might not be the most optimal.

Flags:

  • --max-executable-size the maximum size of heap reserved for executable code (the native code result of just-in-time compiled JavaScript).
  • --max-old-space-size the maximum size of heap reserved for long term objects
  • --max-semi-space-size the maximum size of heap reserved for short term objects
like image 180
Esailija Avatar answered Sep 22 '22 06:09

Esailija