gpt4 book ai didi

javascript - NodeJS 脚本中的注释是否可能会造成内存问题?

转载 作者:IT老高 更新时间:2023-10-28 23:17:10 25 4
gpt4 key购买 nike

我编写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() 代码证明的那样,所有注释都作为函数源代码的一部分保存在内存中,在函数外部的 Node 模块中是模块函数。您可以在构建步骤中去掉注释。

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

关于javascript - NodeJS 脚本中的注释是否可能会造成内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27897938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com