2015-10-15 55 views
1

看起來好像我在下面的函數中有內存泄漏,因爲腳本在運行時吃了大量的內存。任何人都可以發現內存泄漏?這個函數有沒有內存泄漏?

Base.prototype.optimize = function(configurations, data, investment, profitability, callback) { 
    var self = this; 

    process.stdout.write('Optimizing...'); 

    // Exclude configurations that have already been backtested. 
    self.removeCompletedConfigurations(configurations, function() { 
     var configurationCompletionCount = -1; 
     var configurationsCount = configurations.length; 

     async.each(configurations, function(configuration, asyncCallback) { 
      configurationCompletionCount++; 
      process.stdout.cursorTo(13); 
      process.stdout.write(configurationCompletionCount + ' of ' + configurationsCount + ' completed'); 

      // Instantiate a fresh strategy. 
      var strategy = new self.strategyFn(); 

      // Backtest the strategy using the current configuration and the pre-built data. 
      var results = strategy.backtest(configuration, data, investment, profitability); 

      // Record the results. 
      var backtest = { 
       symbol: self.symbol, 
       strategyName: strategy.constructor.name, 
       configuration: configuration, 
       profitLoss: results.profitLoss, 
       winCount: results.winCount, 
       loseCount: results.loseCount, 
       tradeCount: results.winCount + results.loseCount, 
       winRate: results.winRate 
      }; 
      Backtest.collection.insert(backtest, function(error) { 
       // Ensure memory is freed. 
       strategy = null; 
       results = null; 
       backtest = null; 

       asyncCallback(error); 
      }); 
     }, function(error) { 
      if (error) { 
       console.log(error.message || error); 
      } 
      process.stdout.cursorTo(13); 
      process.stdout.write(configurationsCount + ' of ' + configurationsCount + ' completed\n'); 
      callback(); 
     }); 
    }); 
}; 

修復它的指針會很棒!

+0

如果你沒有實例化一個新的策略(沒有回測/插入),循環是否仍然吃這麼多的內存? – Armfoot

+1

我猜'async.each'工作在副本上,而不是實際的對象。所以多個副本可能會導致內存泄漏。 – Minato

+0

@MubashirHanif你釘了它!非常感謝!我決定使用async.series()代替,內存使用量減少了50%。如果你想發佈這個答案,我會給你信用。 –

回答

1

我想async.each工作在副本,而不是實際的對象。所以多個副本可能會導致內存泄漏。