NSMutable对象:removeAllObjects与containsObject速度

时间:2013-04-21 13:42:59

标签: ios optimization

免责声明:我对iOS开发相对较新。我正在为这个项目使用ARC。

我想知道哪些操作更快,为什么?

if([selectedIndexes containsObject:indexPath]) {
    [selectedIndexes removeAllObjects];
    for(int i=0; i<self.options.count; i++) {
        [selectedIndexes addObject:[NSIndexPath indexPathForItem:i inSection:0]];   
    }
} 

NSIndexPath *indexPath;
if([selectedIndexes containsObject:indexPath]) {
    for(int i=0; i<self.options.count; i++) {
        indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        if(![selectedIndexes containsObject:indexPath])
            [selectedIndexes addObject:indexPath];
    }
}

编辑1

问题是,是否执行removeAllObjecs然后再添加东西会更快或者必须检查项目是否已经存在,将其添加到集合中?

1 个答案:

答案 0 :(得分:1)

让我们分析一下(包裹循环的if是相同的,所以我会忽略它):

选项1:
-removeAllObjects:从阵列中删除所有对象,每次释放一次==&gt;最少N次操作==&gt; O(N)
循环进行N次迭代,每次迭代:
*创建NSIndexPath ==&gt; O(1)
*将索引路径添加到数组末尾==&gt; O(1)
==&GT; O(N)+ O(N)+ N * O(1)+ N * O(1)= 2O(N)+ 2 * N * O(1)= 4O(N)= O(N)

选项2:
循环进行N次迭代,每次迭代:
*创建NSIndexPath ==&gt; O(1)
*验证数组中是否存在==&gt; O(N)(数组必须假设它可能包含重复)
* if语句也会因为它会被问到N次,并且会破坏循环的分支预测。
**循环中的加法是概率问题(暂时忽略它)
==&GT; N *(O(1)+ O(N)+ O(1))= N * O(N)+ 2 * N * O(1)= O(N ^ 2)

==&GT;平面分析表明第一种选择更好。

如果您使用NSMutableIndexSet代码,则两个选项的代码如下:

//Not tested
//Assume that selectedIndexes is a NSMutableIndexSet
if ([selectedIndexes containsIndex:indexPath.row]) {
    if (self.options.count) {//This could probably be optimised depend on your goal
        [selectedIndexes addIndexesInRange:NSMakeRange(0,self.options.count-1)];
    } else {
        [selectedIndexes removeAllIndexes];
    }
} 

==&GT;这里最坏的情况复杂度可能是O(N)

请随时纠正任何错误的假设或计算