Node.js切片字符串内存
我是:Node.js切片字符串内存,node.js,string,garbage-collection,Node.js,String,Garbage Collection,我是: r=[]; 对于(i=0;i
r=[];
对于(i=0;i<1e3;i++){
a=(i+)。重复(1e6);
r[i]=a.slice(64128);
}
并从记忆中得到了一个。从我们看来,这是因为所有的a
s都保存在GC中,因为它们的一部分被使用了
切片
不保留内存?我试过了,但还是不行。我必须(循环也算蛮力)吗问题
只提到“将每个子字符串复制为一个新字符串”,而没有提到“释放字符串中剩余的可评估必要部分”r = [];
for (i = 0; i < 1e3; i++) {
a = (i+'').repeat(1e6);
r[i] = a.slice(64, 128);
}
const r = [];
for (let i = 0; i < 1e3; ++i) {
const unitStr = String(i);
// choose something other than "1e6" here:
const maxRepeats = Math.ceil(128 / unitStr.length); // limit the size of the new string
// only using the last 64 characters...
r[i] = unitStr.repeat(maxRepeats).slice(64, 128);
}
node --max-old-space-size=8192 my-script.js
const r = new Array(1e3).fill().map((e,i) => outputRepeats(i));
function outputRepeats(idx) {
const OUTPUT_LENGTH = 128 - 64;
const unitStr = String(idx); // eg, '1', '40' or '286'
// determine from which character to start output from "unitStr"
const startIdxWithinUnit = (64 + 1) % unitStr.length; // this can be further optimized for known ranges of the "idx" input
// determine the approximate output string (may consume additional in-memory bytes: up to unitStr.length - 1)
// this can be logically simplified by unconditionally using a few more bytes of memory and eliminating the second arithmetic term
const maxOutputWindowStr = unitStr.repeat(Math.ceil(OUTPUT_LENGTH / unitStr.length) + Math.floor(Math.sign(startIdxWithinUnit)));
// return the exact resulting string
return maxOutputWindowStr.slice(startIdxWithinUnit, OUTPUT_LENGTH);
}