javascript - Node : Is calling functions from require's cache as fast as functions in global scope?

标签 javascript node.js performance caching require

假设我有一个名为 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/

相关文章:

node.js 保持一个小的内存数据库

java - 为什么当我增加 CPU 核心数时,使用 Freemarker 的 Spring Web 应用程序会变慢?

javascript - 通过 onload 在 Canvas 上绘制文本时,文本呈颗粒状/模糊

node.js - 如何在node.js中检测是否按下了某个键?

javascript - 如何在由框架创建的 <input> 标记中显示不 chop 的文本

javascript - 实现: Phone number validation fails with google-libphonenumber

ruby - ruby 中的大数组操作非常慢

c++ - 算法与预编译引用实现的速度比因计算机而异

javascript - Bootstrap : how to make scrollable list with fixed height in percents

javascript - 如何通过点击谷歌地图中的标记来显示图像