N
N
nikotin772015-12-08 15:32:15
Node.js
nikotin77, 2015-12-08 15:32:15

It would seem a simple loop, but how to implement it correctly?

Hello!
I've already broken my head, maybe someone will tell you.
There is the following code that conveys the essence of the problem:

var body = "";
for(var i=0; i<=5000; i++) {
  body += "if(str==='value" + i + "') 1==1;\n";
}
body += "return str;";

var f1 = new Function("str", body);
var f2 = new Function("str", body);

console.log(f1('test1'));
console.log(f2('test2'));

// main loop
for(var i=0; i<100000; i++) {
  f1("string");
  f2("string");
  console.log(i);
}
console.log("fin!");

My program result:
test1
test2
1
2
3
.
.
~1971

The goal is to execute two functions f1 and f2 100000 times in a loop.
Yes, the functions are big.
At me this cycle is interrupted on approximately 2000 iterations (give or take).
Why it is interrupted to find out succeeded - Out of memory.
The question is how to build the code so as not to run into OOM.
My version of NodeJS is 5.0.0, win7, 4GB of memory.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yeti357, 2015-12-10
@yeti357

setImmediate try. setImmediate will put the function passed to it in the eventloop execution queue. those. Each of these functions will be called in one of the following measures, when it is convenient. The point is that your 100k functions will be distributed over time and over cycles, and will not be executed in one cycle, tightly blocking the entire eventloop, not allowing you to call any asynchronous function (response from the database, request to the server, etc.).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question