NodeJS脚本的注释是否可能会产生内存问题?

Ion*_*zău 11 javascript memory ram comments node.js

我编写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;
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

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


例子

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

function foo () {
    // Hello World comment
    return 10;
}

console.log(foo.toString());
Run Code Online (Sandbox Code Playgroud)

输出:

$ node index.js 
function foo() {
    // Hello World comment
    return 10;
}
Run Code Online (Sandbox Code Playgroud)

另一个例子是生成lorem ipsum200万行然后在最后一行console.log(1).

所以,该文件看起来像:

 // long lorem ipsum on each line
 // ...
 // after 2 million lines
 console.log(1)
Run Code Online (Sandbox Code Playgroud)

运行上面的脚本我得到:

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

这发生在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
Run Code Online (Sandbox Code Playgroud)

Esa*_*ija 5

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

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

  • @Esailija用于节点代码,没有理由不手动编写原始js. (2认同)