【问题标题】:Fastest way to iterate through an NSArray with objects and keys使用对象和键迭代 NSArray 的最快方法
【发布时间】:2010-03-31 01:50:03
【问题描述】:

我在下面有一个名为“objects”的 NSArray,arrayCount = 1000。遍历这个数组大约需要 10 秒。有没有人有更快的方法来遍历这个数组?

for (int i = 0; i <= arrayCount; i++) {
    event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue];
    event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue];
}

【问题讨论】:

    标签: objective-c ios performance nsarray iteration


    【解决方案1】:

    迭代 NSArray 的最快方法是使用 fast enumeration。我的情况是:

    for (id object in objects) {
        event.latitude = [[object valueForKey:@"CLatitude"] floatValue];
        event.longitude = [[object valueForKey:@"CLongitude"] floatValue]
    }
    

    【讨论】:

      【解决方案2】:

      看起来 valueForKey 返回的数组在每次迭代时都是相同的,因此请尝试在循环外获取对它们的引用:

      NSArray *latitudes = [objects valueForKey:@"CLatitude"];
      NSArray *longitudes = [objects valueForKey:@"CLongitude"];
      for (int i = 0; i <= arrayCount; i++) {
          event.latitude = [[latitudes objectAtIndex:i] floatValue];
          event.longitude = [[longitudes objectAtIndex:i] floatValue];
      }
      

      但是循环的意义何在?最后,不就是将事件属性设置为两个数组中的最后一个值吗?另外,如果 arrayCount 是元素的数量,那么循环应该是 i &lt; arrayCount 而不是 i &lt;= arrayCount

      【讨论】:

        【解决方案3】:

        加上其他人在这里所说的,快速枚举更快,因为它迭代 C 数组,而使用 objectAtIndex: 访问索引具有 Objective C 对象消息传递的开销。可以将其视为一次向 NSArray 对象询问其所有内容,而不是单独询问每个对象。

        enumerateObjectsUsingBlock: 方法几乎一样快。块可以很强大,因为您可以将一块代码分配给一个变量并传递它。

        我一直在寻找实际的基准并发现了这个:

        http://darkdust.net/writings/objective-c/nsarray-enumeration-performance

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-02
          • 1970-01-01
          • 2010-11-08
          • 2019-04-08
          • 2023-04-11
          • 2012-03-03
          • 2023-03-23
          • 1970-01-01
          相关资源
          最近更新 更多