以下是NodeJS代码的示例:
function toMB (byteVal) {
return (byteVal / 1048576).toFixed(2);
}
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
var veryLongString = Array(10000000).join('qweqweqweqweqweqweq');
console.log('Node memory usage after string creation:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
console.log('String memory length: ', toMB(Buffer.byteLength(veryLongString)) + ' MB');
JSON.stringify({'str': veryLongString});
console.log('Node memory usage after "JSON.stringify" appy:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
我得到了以下结果:
Node memory usage: 2.01 MB
Node memory usage after string creation: 183.25 MB
String memory length: 181.20 MB
Node memory usage after "JSON.stringify" appy: 545.37 MB
为什么JSON.stringify应用后内存使用量会增长3倍(!!!)?
代码不使用" veryLongString":
function toMB (byteVal) {
return (byteVal / 1048576).toFixed(2);
}
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
JSON.stringify({'str': Array(10000000).join('qweqweqweqweqweqweq')});
console.log('Node memory usage after "JSON.stringify" appy:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
有相同的结果:
Node memory usage: 2.00 MB
Node memory usage after "JSON.stringify" appy: 545.36 MB
答案 0 :(得分:-1)
行:
JSON.stringify({'str': Array(10000000).join('qweqweqweqweqweqweq')});
创建包含json的新字符串对象。像这样:
{"str":"qweqweqweqweqweqweq.........."}
现在我们有两个字符串:)