I write NodeJS libraries and I usually put JSDoc comments in the code, generating documentation then.
So, my code looks like this:
/**
* 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;
};
When this script will be required from another NodeJS script, will the comment above be loaded in the RAM?
So, do the big comments affect the memory somehow?
I guess the NodeJS scripts are parsed and irrelevant things (e.g. comments) are not kept in the memory. Is this true?
So, in conclusion, can such comments create any memory issues?
Stringifying a function, the comment is printed too:
function foo () {
// Hello World comment
return 10;
}
console.log(foo.toString());
Output:
$ node index.js
function foo() {
// Hello World comment
return 10;
}
Another example is to generate lorem ipsum
on 2 million lines and then, on the last line console.log(1)
.
So, the file looks like:
// long lorem ipsum on each line
// ...
// after 2 million lines
console.log(1)
Running the script above I get:
$ node run.js
FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory
Aborted (core dumped)
This happened on a 16GB RAM machine.
I also compared the performance of a simple console.log(1) file with one that has lot of comments:
$ 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
As your .toString()
code prooves, all comments are kept in memory as a part of the function source code, which in node modules outside a function is the module function. You can strip comments out in your build step.
V8 keeps the source in memory because it is the most compact representation of the function, the AST and other intermediate representations are created on the fly as needed and then thrown away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With