Ped*_*o A 10 javascript memory string out-of-memory
好奇我在Javascript中可以获得的最大字符串长度是什么,我今天在我的Firefox 43.0.1上测试了它,在Windows 7中运行.我能够构建一个长度很长的字符串2^28 - 1,但是当我尝试创建一个字符串时另外还有一个字符串,Firebug向我展示了"分配大小溢出"错误,这意味着该字符串必须小于256 MB.
这对所有浏览器,所有计算机,所有操作系统都是一样的,还是依赖于它?
我创建了以下代码片段以找出限制:
(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);
}
})();
Run Code Online (Sandbox Code Playgroud)
如果您运行的是其他浏览器/操作系统,我希望看到您的结果.我的结果是最大字符串长度是268435455.
PS:我四处寻找答案,但我发现的最新话题是2011年,所以我正在寻找更新的信息.
Tam*_*dus 12
当您看到256*2**20字符在字符串中时,这并不意味着分配了256兆字节的内存.JavaScript将每个字符存储在两个字节上(因为它是由规范进行的utf16编码).
今天的浏览器(甚至是IE)以高级方式存储字符串,最常用的是使用绳索数据结构.
s+s不一定使用两倍的内存s通过检查IE和Chrome中的一些运行,我会说他们都对字符串使用了一些懒惰的评估,并会尝试偶尔扩展它们.运行以下代码段后,没有一个浏览器使用的内存比以前多.但是,如果我试图操纵存储window.LONGEST_STRING在控制台中,IE会抛出一个内存不足错误,并且chrome会冻结一段时间,并消耗大量内存(> 2 GB).
ps:在我的笔记本电脑上,IE11的最大字符串大小为4 GB,Chrome的容量为512 MB
IE11
Chrome47
var real_console_log = console.log;
console.log = function(x) {
real_console_log.apply(console, arguments);
var d = document,b=d.body,p=d.createElement('pre');
p.style.margin = "0";
p.appendChild(d.createTextNode(''+x));
b.appendChild(p);
window.scrollTo(0, b.scrollHeight);
};
function alloc(x) {
if (x < 1) return '';
var halfi = Math.floor(x/2);
var half = alloc(halfi);
return 2*halfi < x ? half + half + 'a' : half + half;
}
function test(x) {
try {
return alloc(x);
} catch (e) {
return null;
}
}
function binsearch(predicateGreaterThan, min, max) {
while (max > min) {
var mid = Math.floor((max + min) / 2);
var val = predicateGreaterThan(mid);
if (val) {
min = mid + 1;
} else {
max = mid;
}
}
return max;
}
var maxStrLen = binsearch(test, 10, Math.pow(2, 52)) - 1;
console.log('Max string length is:');
console.log(maxStrLen + ' characters');
console.log(2*maxStrLen + ' bytes');
console.log(2*maxStrLen/1024/1024 + ' megabytes');
console.log('');
console.log('Store longest string');
window.LONGEST_STRING = alloc(maxStrLen);
console.log('Try to read first char');
console.log(window.LONGEST_STRING.charAt(0));
console.log('Try to read last char');
console.log(window.LONGEST_STRING.charAt(maxStrLen - 1));
console.log('Try to read length');
console.log(window.LONGEST_STRING.length);Run Code Online (Sandbox Code Playgroud)