tags:

views:

57

answers:

1

I find myself needing to synthesize a ridiculously long string (like, tens of megabytes long) in JavaScript. (This is to slow down a CSS selector-matching operation to the point where it takes a measurable amount of time.)

The best way I've found to do this is

var really_long_string = (new Array(10*1024*1024)).join("x");

but I'm wondering if there's a more efficient way - one that doesn't involve creating a tens-of-megabytes array first.

+1  A: 

Simply accumulating is vastly faster in Safari 5:

var x = "1234567890";
var iterations = 14;
for (var i = 0; i < iterations; i++) {
  x += x.concat(x);
}
alert(x.length); // 47829690

Essentially, you'll get x.length * 3^iterations characters.

Chuck
i would love to see other's faces when `alert(x);` just splash in their screen... :P
Garis Suero
They'll probably think they've been haxed. Try it with `var x = '<BUFFER OVERFLOW>';`. Who knows, it might even cause one.
MooGoo
I did manage to kill a Chrome content process with the original construct
Zack
Your approach is also vastly faster with Firefox. I plotted it; they both take time proportional to the length of the string, but the Array technique becomes unacceptably slow at 2^20 bytes (one megabyte, not quite enough) where the concatenation technique is still tolerable out to 2^26 or so (64 megabytes, way more than I need).
Zack