javascript - 主干是否对集合中的所有元素或仅添加的元素进行排序

标签 javascript performance sorting backbone.js collections

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

  1. 缓存它们并将它们批量添加到集合中,将 20 种合并为 1
  2. 默默地将模型添加到集合中,并且 debouncing我在每次添加时进行排序的调用(因此最后只调用一次)

所以我想知道 2 是否可行,因为它更容易实现,如果有更好的解决方案我还没有想到。谢谢!

最佳答案

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

您可以使用 debounce 覆盖 add 方法并自己调用 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();
}

关于javascript - 主干是否对集合中的所有元素或仅添加的元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098458/

相关文章:

javascript - 使用 javascript 创建动态表单

c++ - 速度和内存的比较

java - 使用 Java 进行排序和二分搜索

javascript - Dojo.query 删除类

javascript - 如何使用 Twitter 的 Bootstrap 调用 javascript 函数?

javascript - PHP 对 Javascript 的验证

linux - 为什么 'wget --page-requisites' 非常慢

java - 使用 Teradata 通过 Java Web 应用程序进行 OLTP 操作

javascript - 当我使用冒泡排序时,为什么我得到数组中最高值的数字作为我的第一个元素?

arrays - mongodb对文档中数组的子项进行排序