Objective-C中的快速枚举与NSEnumerator [英] Fast Enumeration Vs NSEnumerator in Objective-C

查看:87
本文介绍了Objective-C中的快速枚举与NSEnumerator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经一遍又一遍地看到了这一点,为什么在循环中使用快速枚举比使用nextObject:来使用NSEnumerator更快呢?

I have seen this over and over, why exactly is it faster to use fast enumeration in loops rather than an NSEnumerator using nextObject:.

推荐答案

NSFastEnumeration 是更现代的方法,它利用本地语言支持来提供更有效的枚举.它的工作方式是创建代表当前枚举状态的结构并重复调用

NSEnumerator is the old way to enumerate over collections. It involves creating an object to represent the enumeration, then calling a method on it for every single iteration. While this was perfectly serviceable for many years, it's not terribly efficient, as it involves at least one message send for every iteration of the loop. NSFastEnumeration is the more modern approach, which leverages native language support to provide a much more efficient enumeration. The way it works under the hood is it creates a struct that represents the current enumeration state and repeatedly calls -countByEnumeratingWithState:objects:count: on the collection. This method returns a C array of objects in the objects out-param as well as a counter in the count out-param. This allows the caller to then iterate over the C array. In essence, this means one message call per chunk of objects, which, depending on the collection, could be as efficient as a single message call to get all objects.

如果您有一些看起来像这样的代码

If you have a bit of code that looks like

for (id obj in myArray) {
    [obj doSomething];
}

这被编译器翻译成大致等同于

This gets translated by the compiler into something roughly equivalent to

NSFastEnumerationState __enumState = {0};
id __objects[MAX_STACKBUFF_SIZE];
NSUInteger __count;
while ((__count = [myArray countByEnumeratingWithState:&__enumState objects:__objects count:MAX_STACKBUFF_SIZE]) > 0) {
    for (NSUInteger i = 0; i < __count; i++) {
        id obj = __objects[i];
        [obj doSomething];
    }
}

使用的实际变量是隐藏的,并且对象缓冲区的最大大小也取决于实现,但是这里有基本思想.它将obj-c集合上的迭代转换为C数组上的迭代.

The actual variables used are hidden, and the maximum size of the object buffer is also implementation-dependent, but the basic idea is there. It translates iteration over an obj-c collection into iteration over a C array.

这篇关于Objective-C中的快速枚举与NSEnumerator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆