【发布时间】:2014-06-18 10:03:26
【问题描述】:
对于含糊的标题表示歉意,真的不知道如何描述这个问题。
我最近遇到了一种情况,我必须遍历一个对象数组来比较多个值,我选择在 for 循环中使用 for 循环来比较每个对象与其他每个对象。
虽然这适用于小型阵列,但一旦我的阵列变得更大(比如 10,000 个对象),性能往往会成为一个大问题。
这个数组包含这些类型的对象:
[{ char: '_', from: 0, to: 2, chrLength: 2 },
{ char: '_', from: 0, to: 7, chrLength: 7 },
{ char: 'a', from: 1, to: 3, chrLength: 2 },
{ char: 'a', from: 1, to: 6, chrLength: 5 },
{ char: '_', from: 2, to: 7, chrLength: 5 },
{ char: 'a', from: 3, to: 6, chrLength: 3 }]
我的想法是我只能选择from 和to 不与任何其他对象重叠的对象。 (from 和 to 是另一个数组中的索引)
所以对于示例数组,可能的结果是:
[{ char: '_', from: 0, to: 2, chrLength: 2 },
{ char: 'a', from: 1, to: 3, chrLength: 2 },
{ char: 'a', from: 1, to: 6, chrLength: 5 },
{ char: 'a', from: 3, to: 6, chrLength: 3 }]
我的处理方式如下:
var canUse = true,
posibilities = [];
for(i = 0; i < l; i++) {
canUse = true;
for(var j = 0; j < l; j++) {
if((results[i].from < results[j].from && results[i].to > results[j].to)) {
canUse = false;
break;
}
}
if(canUse) posibilities.push(results[i]);
}
看到较大数组的性能非常糟糕,我想知道是否有更好的解决方案来做到这一点?
【问题讨论】:
-
{ char: '_', from: 2, to: 7, chrLength: 5 }不应该出现在结果中吗? -
@LIUFA:不,因为
{ char: 'a', from: 3, to: 6, chrLength: 3 }适合它。 -
@Jashwant 不太清楚你的意思,你能提供一个小例子吗?
-
@woutr_be,抱歉误解了您的问题。删除了我的评论。
-
正确的数据结构会有所帮助。 en.wikipedia.org/wiki/Interval_tree
标签: javascript arrays performance object for-loop