Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

求教关于js内存释放的问题。

最近在写一个chrome插件
有一个简单的功能分2步是这样:

  1. 从站点提取链接遍历所有详情页面(目前2000+ 每天几十个递增),提取关键数据生成数组对象。
  2. 从生成数组对象判断是否有other_href字段,如果有的话,请求这个other_href解析返回的html获得需要的数据,保存在对象上。

上面2步的请求都是用axios.get,请求拿到的result.data只进入一个解析函数返回解析对象,没有他用。
现在遇到的问题是第二步的other_href是从第一步的result.data解析出来,可能是这个原因导致第一步请求回来的html不能从内存中释放,只开1000多个页面插件就因为内存溢出崩溃了。
打开内存快照里面堆满了<!DOCTYPE html> ...,我测试过如果不对这个other_href进行处理,内存会自动释放维持在300M左右。
我的解析函数只是对字符串进行截取处理

function parseDetailsHtml(html) {

  function getOthersHref(htm) {
    const index = htm.indexOf('name="description"'),
      lastIndex = htm.indexOf('<', index),
      match = (htm.substring(index, lastIndex + 1) || '').match(/>(.+?)</) || [];
    return (match[1] || '').trim();
  }

  //... 其他提取函数

  return {
    others_href: getOthersHref(html),
    ...// 同getOthersHref的[字段名]:[函数名](html)
  };
}

难道这样也能产生引用造成不能释放吗?

现在完全搞不懂应该怎么做了。
111111.png
2222222.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

还真有可能是返回的字符串在底层对原字符串进行了引用导致未被 GC。参见这篇文章 奇技淫巧学 V8 之六,字符串在 V8 内的表达,文中提到,对原 string 进行 substring/slice 底层依然会保留完整的原字符串在堆上的。

就这个问题有一个办法可以规避,用 String.fromCharCode(str.charCodeAt(i)) 转成每个字符的 unicode 再转回去。

就这个问题有一个办法可以规避,可以获取每个字符然后重新造字符串来消除底层 SliceString 的结构。

  function getOthersHref(htm) {
    const index = htm.indexOf('name="description"'),
      lastIndex = htm.indexOf('<', index),
      match = (htm.substring(index, lastIndex + 1) || '').match(/>(.+?)</) || [];
    return cloneStr((match[1] || '').trim());
  }

  //function cloneStr(str) {
  //   let copied = '';
  //   for(let i=0; i<str.length; i++) {
  //      copied += String.fromCharCode(str.charCodeAt(i));
  //   }
  //   return copied;
  //}
  const cloneStr = str => [...str].join('');

还好你的 href 也不会很长,这样并不会影响性能。


做一个实验,证明 slice substring match trim 后最终返回的字符串仍然在底层引用了原字符串。

批注 2020-06-13 230909.jpg

clone 后貌似还有俩内部的 regexp_last_match_info 在引用者。

image.png

随便运行一个正则,没了,貌似是系统内部保存了最后一次正则相关的内容?

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...