1

I need to concat hundreds of Javascript strings like this:

var result = '';
for (var i = 0; i < 300; i ++ ) {
    result += DATA[i] + 'Some Dynamic Text';
}

The DATA[i] is pretty large (Like 300KB or more, it's image's base64 represents).

When I execute this code, the browser pops up an memory overflow error.(The break point is result += DATA[i])

How can I optimize this code to avoid this kind of memory issue ?

==== EDIT ====
I didn't make it clear before, so you can consider the DATA[i] is pretty large and I can't change it. Every concat is also append some dynamic text.

WoooHaaaa
  • 19,732
  • 32
  • 90
  • 138

3 Answers3

0

You can debug using a try {} catch:

var result = '';
for (var i = 0; i < 300; i ++ ) {
    try {
      result += DATA[i];
    }
    catch ( e ) {
        console.log('An error occured on DATA[' + i + ']');
        console.log('Value:' + DATA[i]);
        console.log(e);
    }
}

Why would you store an image in base64 and send it to the front end, because you want to store it offline? Isn't that that cache control is for?

Without any more information i cannot suggest you to use that approach :(

But rater look into how to set a long lasting cache on the image itself.


Btw, you can use Array.join if DATA is a native array:

var result = DATA.join('');

If DATA is an array like object (arguments, {'0': 1, '1': 2, length: 2}) you can use:

var result = [].join.call(DATA, '');

This want solve your memory overflow, but will be faster.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

Please look here .. This should help you

Javascript and VERY LONG string

Also please look at Javascript StringBuilder at -

http://www.codeproject.com/Articles/12375/JavaScript-StringBuilder

Community
  • 1
  • 1
abipc
  • 997
  • 2
  • 13
  • 35
-1

What if you use

result = DATA.join("");
Krasimir
  • 13,306
  • 3
  • 40
  • 55
  • 1
    Obviously this won't work since the same amount of memory is required for the operation. – Joren Aug 12 '13 at 10:42
  • @Joren: Thing is, though...it's not. With the loop, each concat creates another string. If we go with the OP's numbers, 300KB * 300 == 90MB total; building `result` by catting creates ~150x that (over 13GB!) in garbage over the course of 300 concats. Depending on how the implementation's GC works (which ECMA doesn't specify), that garbage might stick around til the browser gets control back. `.join()`, on the other hand -- particularly since it's typically implemented in native code -- almost certainly knows how to create a string without hundreds of intermediate objects. – cHao Aug 12 '13 at 16:14