ReMiDo
ReMiDo

Reputation: 21

Concatenation consumes a lot of memory, how can I optimize it?

Concatenation consumes a lot of memory. If we consider that the character takes ~2 bytes, then the resulting line of code should take about ~20 MB, but when the code presented below works, the page consumes about 1GB. Tried to use Join, or perform the operation s + = 'q'; in function, etc., nothing helps. How can I optimize, for example in ".net" there is a StringBuilder?

var i = 0
       var s = "q";
   while (i <10000000) {
     s + = 'q';
 
     i ++;
   }

P.S.

let str = Array (10000000) .fill (`g`) .join``;

or

'g'.repeat (10000000)

not suitable, need concatenation.

Upvotes: 1

Views: 88

Answers (2)

Maxim T
Maxim T

Reputation: 1282

Try to make a Http request to the web server which can do this operation and return only the result. I would also try a web worker (new browsers support it), but i'm not sure about memory consumption. But it won't use the UI thread.

And i would break this operation into a set of smaller ones using a setTimeout, making for example 100 100000 character strings, and then concantenate them instead of concantenating 10000000 one char strings.

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32202

You could still use join - you don't need to create the whole array in one go with fill:

var i = 0;
var a = [];
while (i <10000000) {
    a[i] = 'q';
    i++;
}
var s = a.join('');

That way you can "concatenate" whatever characters (or larger strings) are needed into the elements of the array, then finally join them all in one go in one operation.

Upvotes: 1

Related Questions