Search code examples
iosobjective-carraysnsnull

isEqual: and isKindOfClass: - Which is faster?


For various reasons, in order to keep an array's indexes aligned with other things, I have [NSNull null] inside the array. Like this:

NSArray *arr = @[obj1, obj2, obj3, [NSNull null], obj4];

There are two methods I'm considering using when iterating through the array to make sure I ignore the null value, but I'm not sure which is faster.

Method 1

for (id obj in arr) {

    if (![[NSNull null] isEqual:obj]) {

        //Do stiff
    }
}

Method 2

for (id obj in arr) {

    if ([obj isKindOfClass:[MyObject class]]) {

        //Do stiff
    }
}

My question is: Since I'm iterating through this array to appropriately handle a tiled scroll view (therefore it's being executed many times as the user scrolls and it's crucial that it runs as quickly as possible), which one of these methods is faster?


Solution

  • [NSNull null] is a singleton, so the easiest things to do is to check if the object pointer is the same.

    If you really want to be fast, do this:

    for (id obj in arr) {
        if ([NSNull null]!=obj) {
            //Do stuff
        }
    }  
    

    BUT it's unlikely that you'll see ANY difference for a visual interface, as we are talking about a very very small difference.

    An option discussed in the comments is to put [NSNull null] in a local variable to speed up checks, but it's possible that the compiler does it for you, so I'm just putting this here for reference:

    NSObject *null_obj=[NSNull null];
    for (id obj in arr) {
        if (null_obj!=obj) {
            //Do stuff
        }
    }