以下是NodeJS代码的示例:
function toMB (byteVal) {
return (byteVal / 1048576).toFixed(2);
}
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
Array(10000000).join('qweqweqweqweqweqweq');
var sec = 0;
setInterval(function(){
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB (after', ++sec + ' sec.)');
}, 1000);
我得到了以下结果:
Node memory usage: 2.00 MB
Node memory usage: 183.31 MB (after 1 sec.)
Node memory usage: 183.32 MB (after 2 sec.)
Node memory usage: 183.32 MB (after 3 sec.)
...
Node memory usage: 183.83 MB (after 128 sec.)
Node memory usage: 183.83 MB (after 129 sec.)
Node memory usage: 183.83 MB (after 130 sec.)
Node memory usage: 2.13 MB (after 131 sec.)
Node memory usage: 2.21 MB (after 132 sec.)
Node memory usage: 2.21 MB (after 133 sec.)
垃圾收集器可用内存。 但是如果我使用相同字符串长度的JSON.stringify:
function toMB (byteVal) {
return (byteVal / 1048576).toFixed(2);
}
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB');
JSON.stringify(Array(10000000).join('qweqweqweqweqweqweq'));
var sec = 0;
setInterval(function(){
console.log('Node memory usage:', toMB(process.memoryUsage()['heapUsed']) + ' MB (after', ++sec + ' sec.)');
}, 1000);
我得到了以下结果:
Node memory usage: 2.00 MB
Node memory usage: 364.22 MB (after 1 sec.)
Node memory usage: 364.24 MB (after 2 sec.)
Node memory usage: 364.24 MB (after 3 sec.)
...
Node memory usage: 365.60 MB (after 482 sec.)
Node memory usage: 365.60 MB (after 483 sec.)
Node memory usage: 365.60 MB (after 484 sec.)
Node memory usage: 2.21 MB (after 485 sec.)
Node memory usage: 2.21 MB (after 486 sec.)
为什么时差(485 vs 131)如此之大?