假设我有一个名为 external.js 的文件:
// external.js
//define a print function and make it public
module.exports.print = function(text) {
console.log(text)
}
然后我有一个名为 main.js 的文件:
// main.js
// call require('./external.js').print so that it'll be in the require's cache
require('./external.js').print('I am now in the cache')
// and define a function equivalent to print in the global scope
function localPrint(text) {
console.log(text)
}
// Finally, define two functions which use the localPrint and the print in external.js
function echo1(text) {
require('./external.js').print(text)
}
function echo2(text) {
localPrint(text)
}
echo1 和 echo2 的性能有什么区别吗?
我敢说不会有。访问全局函数应该与 require 缓存中的函数一样快。你说什么?
最佳答案
Will there be any difference in performance between echo1 and echo2?
也许是一个微不足道的小,是的。 echo1
进行了不必要的函数调用(至少一次,require
可能进行了多次其他调用)和不必要的属性查找(在返回的对象上)(再次强调,至少一个;require
可能需要进行几次属性查找才能在缓存中找到您的资源。
这是否重要完全是另一个问题。
我可能会这样做:
var print = require('./external.js').print;
或者,如果您确实更喜欢另一个名称:
var echo = require('./external.js').print;
或者如果有理由结束调用:
var print = require('./external.js').print;
function echo(text) {
print(text);
}
关于javascript - Node : Is calling functions from require's cache as fast as functions in global scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877297/