Using inline require

牧云@^-^@ 提交于 2019-12-24 00:34:03

问题


If I use an inline require, like this:

function something(...paths) {
  return require('path').join(...paths);
}

something('etc', 'etc');

Would the engine require in every call? Example:

let i = 10;
while (--i)
  something(i, 'etc');

Thank you.


回答1:


The system will call require() each time through your loop, but modules loaded with require() are cached and the module loading code is only run the first time the module is loaded. So, while there is a slight bit of extra overhead calling require('path'), it is only to look up that module name in the cache and return the cached module handle. It does not need to load, parse and run the module each time you call require().

That said, it still would be better to be in the habit of this:

const pathModule = require('path');

function something(...paths) {
  return pathModule.join(...paths);
}

The other downside to the way you were doing it, is that the first time the path module is loaded, the system will use synchronous file I/O to load it which is not a good idea in a multi-user server. The file I/O just happens the first time, but still not a great practice. Better to get the synchronous I/O out of the way at server initialization time.



来源:https://stackoverflow.com/questions/46045675/using-inline-require

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!