Fetch API 在 Chrome 中泄漏内存 [英] Fetch API leaks memory in Chrome

查看:39
本文介绍了Fetch API 在 Chrome 中泄漏内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以最简单的方式使用 fetch-API 时,Chrome 无法正确进行垃圾收集.我做错了吗?

When using the fetch-API in the most simple way, Chrome is not garbage collecting correctly. Am I doing something wrong?

for (i = 0; i < 100; i++) {
  fetch('https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg')
    .then(response => {
      console.log('Memory-bloating')
    })
}

https://jsfiddle.net/dozrpcvj/12/

这个 JSFiddle 用 1.4GB 填充内存,直到您手动进行垃圾收集或关闭选项卡后才会释放.如果将迭代次数增加到 1000 次,它会下载"14GB(从自己的磁盘),而不是垃圾收集,而是开始填充磁盘上的交换文件.

This JSFiddle fills the memory with 1.4GB, which doesn't release until you either manually garbage collect or you close the tab. If you increase the number of iterations to 1000 it "downloads" 14GB (from the own disk) and instead of garbage collecting it starts filling the swap file on disk.

是我做错了什么还是 Chrome 中的错误?使用 Safari 进行测试时,它也会用 1.4GB 填充硬盘驱动器,但一旦完成就会开始垃圾收集.

Am I doing something wrong or is this a bug in Chrome? When testing with Safari, it also fills the hard drive with 1.4GB, but starts garbage collecting as soon as it's done.

PS.您不能使用内存分析器,因为它告诉您只使用几 MB 的数据,即使活动监视器或 Chrome 自己的任务管理器显示 1.4GB.

PS. You can't use the memory profiler, since that tells you that you only use a few MB of data, even if the Activity Monitor or Chromes own Task Manager says 1.4GB.

推荐答案

你没有做错;只是当你同时调用一堆 Promise 时,会占用大量内存.如果你想确保它不使用太多内存——并且你愿意让它花更长的时间——你可以把它全部放在一个异步函数中并这样做:

You're doing nothing wrong; it's just that when you call a bunch of promises at the same time, that's going to use a lot of memory. If you want to make sure that it doesn't use as much memory--and you're willing to have it take longer--you could put this all inside of an async function and do this:

for (i = 0; i < 100; i++) {
  await fetch('https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg')
  console.log('Memory-bloating')
}

这篇关于Fetch API 在 Chrome 中泄漏内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆