tags:

views:

92

answers:

4

I need to construct a long string with javascript. Thats how i tried to do it:

var html = '<div style="balbalblaba">&nbsp;</div>';
for(i = 1; i <= 400; i++){
   html+=html;
};

When i execute that in firefox its taking ages or makes it crash. what is the best way to do that? What is generally the best way to construct big strings in JS.

can someone help me?

+6  A: 
KennyTM
+1 but should be "...any browsers and any computers in the _known_ universe..."
thx for the link! Yeah i have made an error while simplifying my example for the post! Thanks a lot for the explanation! How does it comes that it is faster to flatten a array, then to join some strings?
meo
@david: `Array.join` was more efficient than `+=` for long string. I don't know the situation of JS optimization now but it's still better to build a string using `.join` to cater for older browsers.
KennyTM
oh i don't care about the old browsers for this, its just a visual experiment. I fill the screen with pixels made out of divs. (window.size / pixel.size (10x10)). Now it works, but still its very slow. I wonder how i could optimize this... But that, is gonna be an other question soon. Thx anyway for your excellent answer
meo
A: 
var src = '<div style="balbalblaba">&nbsp;</div>';
var html = '';
for(i = 1; i <= 400; i++){
   html=+src;
};

Your code is doubling the string 400 times.

Devon_C_Miller
I think that `html=+src` makes `html` equal to 0.
Gabe
+1  A: 

Another way to do it is by create an Array of stings then using Array.join(''). This is effectively the Python way of building strings, but it should work for JavaScript as well.

Kathy Van Stone
+4  A: 

String concatenation is very slow in some browsers (*cough*IE6*cough*). Joining an array should be much quicker than looping with concatenation:

var arr = new Array(401);
var html = arr.join('<div style="balbalblaba">&nbsp;</div>');
Andy E
You can do away with the `new ` prefix, as just `Array(401)` will suffice.
J-P
@J-P: you can, but the behaviour is exactly the same and I generally prefer to treat the `Array()` object as a constructor when creating arrays with it :-)
Andy E
+1 this is the idiom for string multiplication in JS.
bobince
+1, but get rid of temp var: `html = Array(401).join('...')`
stereofrog
@sterofrog: As I have done, when writing this into my own code. Sometimes I prefer to separate in answers for extra clarity. To each his own, right? ;-)
Andy E