L
L
LokerdLife12020-11-11 17:23:19
JavaScript
LokerdLife1, 2020-11-11 17:23:19

How to organize an infinite loop (or infinite recursion) in Node.JS without a memory leak?

Good afternoon!
The task is to develop a JavaScript program (in principle) with an unlimited work cycle using Node.JS. There was a problem that the program eats up memory. The best solution was the following code:

loop();
function loop() {
    //Тут произвольный код
    setTimeout(function() {
        loop();
    }, 8);
}

But even here there is a leak (0.5 - 1mb per hour), which is extremely critical. The infinite loop solution did not work because it is extremely difficult to organize a delay between iterations without leakage.
In PHP, the issue is solved simply (if you do not forget to clean the variables in the loop body and periodically run forced cleaning) :
for(;;){
    //Тут произвольный код
    usleep(8000);
}

For the first time, I encountered the problem of a memory leak in JS and could not solve the problem on the fly. Probably someone faced similar?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LokerdLife1, 2020-11-12
@LokerdLife1

Lynn's "Coffeeman" solution ( see comments under question) helped optimize the program! For the first 2-3 hours, the situation was worse than with my solution (I assume that the code has become simpler and the number of iterations per unit of time has increased, thus the speed of eating memory has also increased) , but for reasons I do not understand, after 6-8 hours the memory began to return to the system, and even in what volume (memory consumption decreased from 6.6mb to 3.4mb) . What happened is not clear. The script is working normally. Yes, it still eats up memory, but after a few hours it abruptly gives half to the system. There is something to think about.
For those interested - OS: Ubuntu 18.04.1; platform - Node.JS 8.10; program code:

loop();
function loop() {
    setTimeout(loop, 8);
}

I'm not sure that the problem will not return, because. I do not fully understand the nature of all processes. If someone has experienced this or understands what is happening here (heh) , I will be glad to hear your opinion!

A
Alexey P, 2020-11-11
@ruddy22

Infinite Loop in JS:

while (true) {
  // do something here
}

If we talk about delays, then no one bothers to organize work through (micro) queues and resolve the result through Async / Await.
BUT!
According to air-bnb, resolving async/await in while, forloop is bad practice. Here is the link .
PS
There will be leaks, you can't hide from them! Questions about platform architecture (NodeJS/Browser => V8) and garbage collector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question