gpt4 book ai didi

javascript - 带有 express 的 Node.js 服务器,什么是需要文件和内存的最佳方式

转载 作者:搜寻专家 更新时间:2023-11-01 00:40:32 24 4
gpt4 key购买 nike

因此,为了方便和可读性,在顶部声明变量始终是个好主意;

但是我想知道 js 是如何处理需要文件的。是在声明时全部加载还是在执行时加载?在顶部声明之间是否存在有意义的差异(如果只需要一个“FILE”来运行程序)

var File1 = require('../api/file1.js');
var File2 = require('../api/file2.js');
var File3 = require('../api/file3.js');
var File4 = require('../api/file3.js');
var ManyOtherRequiredFiles = require('..');

if(1){
var file = new File1();
file.run()
}else if(2){
var file = new File2();
file.run()
}else if(3){
var file = new File3();
file.run()
}else{
var file = new File4();
file.run()
}

或者不在顶部声明但在需要时声明:

var ManyOtherRequiredFiles = require('..');

if(1){
var File = require('../api/file1.js');
var file = new File();
file.run()
}else if(2){
var File = require('../api/file2.js');
var file = new File();
file.run()
}else if(3){
var File = require('../api/file3.js');
var file = new File();
file.run()
}else{
var File = require('../api/file4.js');
var file = new File();
file.run()
}

这两个选项在内存方面是否存在有意义的差异?如果是这样,在需要时请求文件是处理事情的最佳方式吗?

如果不是,在顶部声明和创建新实例是否有任何不同或更糟?

var File1 = require('../api/file1.js');
var file1 = new File1();

var file1 = new require('../api/file1.js')();

等;

最佳答案

模块会在您调用 require 函数时立即加载。

每个加载的模块都使用文件的扩展路径作为缓存键进行缓存。

如果您加载同一个文件 5 次,它只会加载一次,因为缓存键将是相同的 - 即使您指定不同的路径,例如“../file.js”或“../../foo/file.js"- 只要这两个路径指向同一个文件,相对于你调用 require 的地方,它就会重新使用已经加载的模块。

Is there a meaningful difference on memory between these two options?;

稍微,但直到您最终加载文件为止。

将另一个模块加载到内存中所使用的内存量可以忽略不计。正是在该模块中使用的代码加起来很快。

例如,您可能有一个只有 3 或 4 行代码的非常小的文件...但该代码可能会循环 10 亿次以上,每次迭代都会使用大量内存。

您不应该担心加载模块所占用的内存,而是您编写的代码所占用的内存。

此外,延迟加载模块的想法对性能的影响比对内存的影响更大。

require 调用相对昂贵,因为它必须同步发生。同步文件访问将阻止应用程序中的一切,直到文件被加载。

正因为如此,加载一个模块占用的内存很小,所以最好在应用程序启动周期的开始加载所有模块。只需让 require 调用位于文件的顶部并完成它即可。

if not, Is declaring and creating new instances up top any different or worse?

如果您在给定模块中只需要一次文件,这几乎没有什么区别

关于javascript - 带有 express 的 Node.js 服务器,什么是需要文件和内存的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164567/

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