延迟加载node.js [英] Lazy loading in node.js

查看:102
本文介绍了延迟加载node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在node.js中使用require()是否等效于延迟加载?

I was wondering if using require() in node.js was the equivalent to lazy loading?

例如,如果我有一个函数需要代码中其他任何地方都不需要的特定node.js包,那么我最好在该函数内部使用require(),以便仅在该函数为叫.

For example if I had a function that required a specific node.js package that wasn't needed anywhere else in my code am I best to use require() inside of that function to include the needed package only when that function is called.

由于我对node.js架构缺乏了解,因此我不确定这是否会带来任何性能改进?我认为它每次与服务器的连接都将使用更少的内存.但是,当它必须读取程序包时,它会增加磁盘的I/O吗,还是将其添加到内存中?

I'm also unsure if this will provide any performance improvements given my lack of understanding around the node.js architecture? I presume it will use less memory per connection to my server. However will it increase I/O to the disk when it has to read the package, or will this be a one off to get it in memory?

如果是这种情况,我应该走多远,我应该尝试以尽可能多的代码编写node.js软件包吗?

If this is the case how far should I take this, should I be trying to write node.js packages for as much code as I can?

推荐答案

require()是按需加载.加载模块后,如果再次运行require()调用,则将不会重新加载该模块.通过将其放入函数而不是顶层模块代码中,可以延迟其加载,或者如果您从未实际调用该函数,则可以避免加载.但是,require()是同步的,并从磁盘加载模块,因此最佳实践是在应用程序启动服务请求之前先加载应用程序启动时需要的任何模块,然后确保在应用程序运行时仅发生异步IO.

require() is on-demand loading. Once a module has been loaded it won't be reloaded if the require() call is run again. By putting it inside a function instead of your top level module code, you can delay its loading or potentially avoid it if you never actually invoke that function. However, require() is synchronous and loads the module from disk so best practice is to load any modules you need at application start before your application starts serving requests which then ensures that only asynchronous IO happens while your application is operational.

节点是单线程的,因此加载模块的内存占用不是按连接的,而是按进程的.一次性加载模块即可将其存入内存.

Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.

只需遵守此处的约定,并在开始处理请求之前在应用程序的顶级范围内需要您需要的模块.我认为这是一种情况,如果您要问是否需要以一种不寻常的方式编写代码,那么您就不需要以一种不寻常的方式编写代码了.

Just stick with the convention here and require the modules you need at the top level scope of your app before you start processing requests. I think this is a case of, if you have to ask whether you need to write your code in an unusual way, you don't need to write your code in an unusual way.

这篇关于延迟加载node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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