来自 NodeJS 脚本的注释是否有可能产生内存问题

Is it possible that the comments from a NodeJS script create memory issues?

本文关键字:内存 问题 有可能 是否 NodeJS 脚本 注释 来自      更新时间:2023-09-26

我编写NodeJS库,通常将JSDoc注释放入代码中,然后生成文档。

所以,我的代码看起来像这样:

/**
 * Sum
 * Calculates the sum of two numbers.
 *
 * @name Sum
 * @function
 * @param {Number} a The first number,
 * @param {Number} b The second number.
 * @return {Number} The sum of the two numbers.
 */
module.exports = function (a, b) {
    return a + b;
};

当另一个 NodeJS 脚本需要此脚本时,上面的注释是否会加载到 RAM 中?

那么,大评论会以某种方式影响记忆吗?

我想 NodeJS 脚本被解析了,不相关的东西(例如注释)不会保存在内存中。这是真的吗?

那么,总而言之,这样的评论会产生任何内存问题吗?


例子

字符串化函数,注释也会打印:

function foo () {
    // Hello World comment
    return 10;
}
console.log(foo.toString());

输出:

$ node index.js 
function foo() {
    // Hello World comment
    return 10;
}

另一个例子是在 200 万行上生成lorem ipsum,然后在最后一行console.log(1) 上生成 。

因此,该文件如下所示:

 // long lorem ipsum on each line
 // ...
 // after 2 million lines
 console.log(1)

运行上面的脚本,我得到:

$ node run.js 
FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory
Aborted (core dumped)

这发生在 16GB RAM 机器上。


我还比较了一个简单的 console.log(1) 文件的性能与一个有很多注释的文件:

$ time node with-comments.js
1
real    0m0.178s
user    0m0.159s
sys 0m0.023s
$ time node no-comments.js
1
real    0m0.040s
user    0m0.036s
sys 0m0.004s

正如您的.toString()代码所证明的那样,所有注释都作为函数源代码的一部分保存在内存中,在函数外部的节点模块中是模块函数。您可以在构建步骤中去除注释。

V8 将源代码保存在内存中,因为它是函数最紧凑的表示形式,AST 和其他中间表示是根据需要动态创建的,然后丢弃。