Curious about what was the maximum string length I could get in Javascript, I tested it myself, today, on my Firefox 43.0.1, running in Windows 7. I was able to construct a string with length 2^28 - 1
, but when I tried to create a string with one more char, Firebug showed me the "allocation size overflow" error, meaning the string must be less than 256 MB.
Is this the same thing for all browsers, all computers, all operational systems, or it depends?
I created the following snippet to find out the limit:
(function() {
strings = ["z"];
try {
while(true) {
strings.push(strings[strings.length - 1] + strings[strings.length - 1]);
}
} catch(err) {
var k = strings.length - 2;
while(k >= 0) {
try {
strings.push(strings[strings.length - 1] + strings[k]);
k--;
} catch(err) {}
}
console.log("The maximum string length is " + strings[strings.length - 1].length);
}
})();
If you are running a different browser/OS, I would like to see your results. My result was The maximum string length is 268435455.
P.S.: I searched around for an answer, but the most recent topic I found was from 2011, so I am looking for a more up-to-date information.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…