nodejs:从 require 的缓存中调用函数是否与全局范围内的函数一样快?

nodejs: Is calling functions from require's cache as fast as functions in global scope?

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

我刚刚做了基准测试:

main.js

// main.js

// call require('./external.js').print so that it'll be in the require's cache
var e = require('./external.js');

// and define a function equivalent to print in the global scope
function localPrint() {
    var hello = "hello";
    return hello;
}

var f = {
  hello : function(){
    var hello = "hello";
    return hello;
  }
}

// Finally, define two functions which use the localPrint and the print in external.js
function echo1() {
    e.hello();
}


function echo2() {
    localPrint()
}

function echo3(){
  f.hello();
}

(function (){
  var times = 100000000;
  var start1 = +new Date();
  for (var i = 0; i < times; i++) {
    echo1('text');
  };
  var stop1 = +new Date();

  var start2 = +new Date();
  for (var i = 0; i < times; i++) {
    echo2('text');
  };
  var stop2 = +new Date();

  var start3 = +new Date();
  for (var i = 0; i < times; i++) {
    echo3('text');
  };
  var stop3 = +new Date();

  console.log('From require', stop1,start1, stop1 - start1);
  console.log('From local', stop2,start2, stop2 - start2);
  console.log('From object', stop3,start3, stop3 - start3);
})();

external.js

// external.js
//define a print function and make it public
module.exports.hello = function() {
    var hello = "hello";
    return hello;
}

结果:

From require 1430050276387 1430050276313 74
From local 1430050276460 1430050276387 73
From object 1430050277569 1430050276460 1109

每个 100M 调用的差异与要求或局部变量(73 和 74 毫秒)相比并不显着。但是,从对象比使用要求慢 15 倍(1109 毫秒)...

使用 NodeJS 强大的模块系统,而不是创建大对象。

希望对您有所帮助,希望它是正确的!