是对集合中的所有元素排序,还是只对添加的元素排序

Does backbone sort all elements in collection or just added ones

本文关键字:元素 排序 添加 集合      更新时间:2023-09-26

我有一个速度问题在我的骨干应用程序在无休止的滚动事件;模型被单独添加到集合中,因此每次都对集合进行排序。我想知道如何优化这一点,并有两个解决方案:

  1. 缓存它们并将它们批量添加到集合中,将20种排序合并为1
  2. 默默地将模型添加到集合中,并在每次添加期间取消对排序的调用(因此最终只进行一次调用)

所以我想知道如果2甚至是可能的,因为它会更容易实现,如果有一个更好的解决方案,我没有想到。谢谢!

您可以使用collection .reset()将多个元素插入到您的集合中,并且只触发一个排序事件。添加的元素将被替换,因此如果现有元素存在,则需要合并它们。

与其缓存条目,不如重写add方法并使用debounce方法自己调用sort。

initialize: function() {
   // if you declare the debounce at the Collection.extend(...) level, it will be
   // global to all objects (if you have 20 collections they all have to stop calling
   // sort before this will fire) so putting it here in initialize is probably wise
   this.sort = _.debounce(function(a, b) {
       /* do your mojo */
   }, 250)
},
add: function(m, opts) {
   if( !m instanceof Backbone.Model ) {
      m = new Backbone.Model(m);
   }
   this.models.push(m);
   // probably need to check for opts here and honor silent?
   this.trigger('add', m);
   // for consistency, not sure if this should come before or after the trigger for "add"
   this.sort();
}

为了确定,您的集合是否因为定义了比较器函数而自动排序?

我试着通读Backbone和Underscore源以确定所使用的排序方法。不幸的是,我读了10分钟后还是看不出来,所以我不知道是否使用了性能较低的排序方法。尽管如此,我还是怀疑排序是不是你的主要障碍。根据我的经验,收集速度问题通常来自于add和update事件对视图的重新渲染。

通过将您的想法与1相结合,

2是非常可能的,只需将新模型添加到数组中,并使用_.debounce每500 ms将数组添加到集合中。请确保传递给debounce的函数也清除了该数组。

因为我使用的是Parse,所以我不得不修改他们的旧版本的Backbone,以便在Collection.add函数中包含options.sort选项:

      if (this.comparator && options.sort !== false) {
        this.sort({silent: true});
      }

所以我添加使用collection.add(model, {sort:false}),然后调用collection.sort()

然而,在我的情况下,我也意识到排序是不必要的(因为模型是按排序顺序添加的),所以我已经完全取消了排序,并在我的无尽滚动条批量加载期间节省了自己约10%的时间。

谢谢!