0

背景

早在 5 月,我就在 WebKit 上报告了一个关于内存保留问题的问题。看起来问题可能是由于 Web Inspector 本身造成的,但我还不相信。

问题

一个问题浮出水面,我的 JavaScript 应用程序实现了“轮询消费者”模式,以便在数据可用时获取数据。问题是记忆被保留并全天增长。JavaScript 逻辑如下所示:

  1. 获取数据并给我回电话
  2. 当我被回调处理数据然后执行步骤 1

这是在 JavaScript 中实现轮询消费者的合理方式吗?顺便说一句,我正在使用 jQuery 的 ajax 函数,这当然可能有它自己的问题。此外,我使用 jQuery 代理作为成功处理程序,因此我认为通过范围保留应该不是问题。我也在不使用代理的情况下观察到了这个问题。一些代码:

FidsDataController.prototype.getFids = function() {
  var self = this;
  $.ajax({
...
    success: function(data) {
      // Do some processing
      // Call back in a short while...
      setTimeout($.proxy(self.getFids, self), 100);
    },
...
  });
);
4

1 回答 1

1

您只有一个 的副本getFids,这很好,但是每次调用它时,您都在创建两个新函数:一个用于成功处理程序,一个来自$.proxy调用。这两个函数在每次调用时都不是唯一的。将它们放在可重用的变量中,您将节省大量额外的函数创建,这应该会大大降低您的内存泄漏可能性。

我们在构造函数中为每个对象创建每个函数的代理版本的示例。重复调用不会产生更多函数:

function FidsDataController() {
  // ...constructor...


  // Proxy these functions just once from the prototype
  this.getFids = $.proxy(this.getFids, this);
  this._getFids_success = $.proxy(this._getFids_success, this);
}

FidsDataController.prototype.getFids = function() {
  var self = this;
  $.ajax({
    success: this._getFids_success;
  });
};

FidsDataController.prototype._getFids_success = function(data) {
  // processing of data
  setTimeout(this.getFids, 100);
};
于 2010-09-14T02:08:12.147 回答