0

This simple code stores 1 million strings (100 chars length) in an array.

function makestring(len) {
    var s = '';
    while (len--) s = s+'1';
    return s;
}

var s = '';
var arr = [];
for (var i=0; i<1000000; i++) {
    s = makestring(100);
    arr.push(s);
    if (i%1000 == 0) console.log(i+' - '+s);
}

When I run it, I get this error:

(...)
408000 - 1111111111111111111 (...)
409000 - 1111111111111111111 (...)
FATAL ERROR: JS Allocation failed - process out of memory

That's strange 1 million * 100 are just 100 megabytes.

But if I move the s = makestring(100); outside the loop...

var s = makestring(100);
var arr = [];
for (var i=0; i<1000000; i++) {
    arr.push(s);
    if (i%1000 == 0) {
        console.log(i+' - '+s);
    }
}

This executes without errors!

Why? How can I store 1 Million objects in node?

2 Answers 2

2

In the moment you move the String generation outside the loop, you basically just create one String and push it a million times into the array.

Inside the array, however, just pointers to the original String are used, which is far less memory consuming then saving the String a million times.

Sign up to request clarification or add additional context in comments.

Comments

0

Your first example builds 1000000 strings.

In your second example, you're taking the same string object and adding it to your array 1000000 times. (it's not copying the string; each entry of the array points to the same object)

V8 does a lot of things to optimize string use. For example, string concatenation is less expensive (in most cases) than you think. Rather than building a whole new string, it will typically opt to connect them i a linked list fashion under the covers.

5 Comments

anyway, 1 Millon strings (~100MB) shouldn't eat all memory
Your math is off. For one, each String has a fair amount of overhead by V8 for bookkeeping (I'm not sure how much - probably on the order of 10 bytes per string). I'm also fairly certain that V8 stores strings in UTF-16 by default (2 bytes per char).
If you want a more memory efficient way of storing large quantities of data, take a look at Node's Buffer class.
Nevir, even if the overhead is 500 bytes per string, 1 Million would be 600 MB, far below the memory limit.
Note that in your example, your makestring function is creating 100 new strings each time (each with a certain amount of overhead), and V8 is probably not flattening them into one object. Chances are that your example actually built 1000000 * 100 string objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.