11

それで、定期的に関数を再帰的に呼び出すための(スタックの成長とパフォーマンスの観点から)より良い方法は何でしょうか?たとえば、200ミリ秒ごとにファイルの内容を読み取りたいとします。私は次の2つの方法を持っていますが、それらが何か違うのだろうかと思っていましたか?

方法1:process.nextTickなしでプレーンolssetTimeoutを使用する

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 に答える