objective-cfast-enumerationnsenumerator

Fast Enumeration Vs NSEnumerator in Objective-C


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


Solution

  • 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];
        }
    }
    

    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.