我开始学习Nodejs,并试图了解它管理内存的方式。我知道有一种叫“垃圾收集器”的东西。
我尝试使用Express JS编写以下小代码:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
let used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`);
})
app.get('/a', (req, res) => {
var array = Array(1e7).fill("a");
delete array;
let used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`);
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})我添加了2条路由。第一个路径没有什么特别之处,只是一段打印内存使用量的代码。
在第二个路径中,我创建了一个巨大的数组,然后将其删除。
我称第一条路线为。我得到了:
The script uses approximately 5.87 MB
然后我调用第二个路由,我得到了:
The script uses approximately 82.2 MB
然后我刷新第一个路由,我得到:
The script uses approximately 4.36 MB
然后,我再次刷新第二个路由。我得到了:
The script uses approximately 80.6 MB
从现在开始,无论我刷新多少次第一个路由,我总是得到:
The script uses approximately 80.65 MB
我知道"delete“关键字只会破坏引用,它不会立即释放内存。
但是GC呢?它在做什么?我等待了超过10分钟,并尝试了第一个路线,它显示几乎相同的结果(> 80MB)
有人能解释一下为什么内存没有减少吗?谢谢你的帮忙
发布于 2020-10-03 02:50:49
大对象总是属于“垃圾回收”的第二代,这就是为什么即使没有引用也能比小对象“存活”得多的原因。
除了delete array;之外,您还可以预先执行array.length = 0;。
https://stackoverflow.com/questions/64175994
复制相似问题