此程序会导致内存泄漏吗?

编程入门 行业动态 更新时间:2024-10-08 06:27:41

此程序会导致<a href=https://www.elefans.com/category/jswz/34/1771154.html style=内存泄漏吗?"/>

此程序会导致内存泄漏吗?

我似乎无法找出导致内存泄漏的原因。我收到“堆内存不足”错误。我试图将所有没有用的变量设置为null,但没有用。我尝试使用简单的forEach函数而不是使用each中的async.js函数,但这也没有用。在任务管理器中查看应用程序的内存使用情况时,其运行时间越长,消耗的内存就越高。但我似乎无法弄清哪些地方没有清理或收集垃圾。

const fs = require('fs')

const mj = require('mathjax-node-sre')
const each = require('async/each')
const colors = require('colors')
const cliProgress = require('cli-progress')
const { JSDOM } = require('jsdom')

mj.config({ displayErrors: false })

console.log('')

const progressBar = new cliProgress.SingleBar({
  format: '  MathML to SRE  ' + colors.cyan('{bar}') + '  {percentage}%  |  {value}/{total} Files',
  barCompleteChar: '\u2588',
  barIncompleteChar: '\u2591',
  hideCursor: true
})

let files = fs.readdirSync('C:/Users/koliva/Desktop/xml2/').filter(file => file.endsWith('\.xml') && !file.endsWith('_sre\.xml'))
let mjErrors = []

progressBar.start(files.length, 0)

each(files, (mml, callback) => {
  try {
    let inputFileName = mml
    let outpuFileName = 'C:/Users/koliva/Desktop/xml2/' + mml.replace('\.xml', '_sre.xml')

    mml = fs.readFileSync('C:/Users/koliva/Desktop/xml2/' + mml, 'utf8')

    mj.typeset({ math: mml, format: 'MathML', svg: true }, data => {
      let sre = new JSDOM(data.svg).window.document.getElementsByTagName('title')[0].innerHTML

      mml = new JSDOM(mml)
      mml.window.document.getElementsByTagName('mml:math')[0].setAttribute('alttext', sre)

      fs.writeFileSync(outpuFileName, mml.serialize().replace(/<\/?body>|<\/?html>|<\/?head>/g, ''))
      progressBar.increment()
      if (data.errors) {
        mjErrors = mjErrors.concat({ 'name': inputFileName, 'errors': data.errors })
      }
      callback()
    })
  } catch (error) {
    callback(error)
  }
}, (err) => {
     // do something
})

回答如下:

nodejs使用的V8引擎在64位计算机上的默认内存限制为~1.5GB。即使系统上有更多可用内存,如果堆分配增加1.5GB,默认情况下,nodejs也会抛出Heap out of memory错误。

[这样运行应用程序时,有一种简单的方法可以通过传递max_old_space_size标志来增加默认内存限制:

#increase to 4gb
node --max-old-space-size=4096 index.js

[如果您想研究堆内存的分配位置和方式,以及是否存在内存泄漏,则可以通过使用chrome的inspect工具检查您的应用程序来轻松实现。

只需使用node --inspect server.js运行您的应用,然后导航至chrome://inspect。在这里,您可以查看随时间推移使用的堆快照。更多详细信息here。

更多推荐

此程序会导致内存泄漏吗?

本文发布于:2024-05-07 10:32:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755843.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!