11

所以我想知道什么是定期递归调用函数的更好方法(就堆栈增长和性能而言)?例如,假设我想每 200 毫秒读取一次文件内容。我有以下两种方法,想知道它们是否有什么不同?

方法一:使用普通ols setTimeout 不带process.nextTick

var fs = require('fs');
(function loop() {
  // Print to time to indicate something is happening
  console.log(new Date().toString());

  // Read a 51MB file
  fs.readFile('./testfile', function (err, data) {
    if (err) console.log(err);
  });

  // Call the same function again
  setTimeout(function () {
    loop();
  }, 200);
})();

方法2:在setTimeout里面调用process.nextTick

var fs = require('fs');
(function loop() {
  // Print to time to indicate something is happening
  console.log(new Date().toString());

  // Read a 51MB file
  fs.readFile('./testfile', function (err, data) {
    if (err) console.log(err);
  });

  // Call the same function again
  setTimeout(function () {
    process.nextTick(function () {
      loop();
    });
  }, 200);
})();

我想知道的是在 setTimeout 中添加 process.nextTick 是否有帮助?调用 process.nextTick 中的函数是否会减轻堆栈的使用?

4

1 回答 1

34

以下简化示例中没有递归:

function test()
{
   console.trace();
   setTimeout(test, 1000);
}

test();

输出(注意堆栈没有增长)

Trace
    at test (/private/tmp/rec.js:3:12)
    at Object.<anonymous> (/private/tmp/rec.js:7:1)
    at Module._compile (module.js:449:26)
    at Object..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function._load (module.js:312:12)
    at module.js:487:10
    at EventEmitter._tickCallback (node.js:238:9)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
于 2012-06-20T08:43:05.160 回答