【问题标题】:Is there a memory leak in this function?这个函数有内存泄漏吗?
【发布时间】:2015-10-15 09:54:35
【问题描述】:

似乎我在以下函数中存在内存泄漏,因为脚本在运行时会消耗大量内存。谁能发现内存泄漏?

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();
        });
    });
};

而且修复它的指针会很棒!

【问题讨论】:

  • 如果你不实例化一个新策略(没有回测/插入),那么循环是否仍然会占用那么多内存?
  • 我猜async.each 作用于副本而不是实际对象。所以多个副本可能会导致内存泄漏。
  • @MubashirHanif 你成功了!太感谢了!我决定改用 async.series(),内存使用量减少了 50%。如果您想将此作为答案发布,我会给您信用。

标签: javascript node.js memory-leaks


【解决方案1】:

我猜async.each 作用于副本而不是实际对象。所以多个副本可能会导致内存泄漏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多