使用内联要求 [英] Using inline require

查看:108
本文介绍了使用内联要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用内联要求,例如:

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');

谢谢.

推荐答案

系统每次通过循环都会调用require(),但是会缓存加载了require()的模块,并且模块加载代码仅在第一次运行时运行模块已加载.因此,尽管调用require('path')会产生一点点额外的开销,但这仅是在高速缓存中查找该模块名称并返回已高速缓存的模块句柄.不需要在每次调用require()时加载,解析和运行模块.

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);
}

这样做的另一个缺点是,第一次加载path模块时,系统将使用同步文件I/O来加载它,这在多用户环境中不是一个好主意.服务器.文件I/O只是第一次发生,但仍然不是一个好习惯.最好在服务器初始化时将同步I/O排除在外.

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.

这篇关于使用内联要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆