3

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?

rebello95
  • 8,486
  • 5
  • 44
  • 65

1 Answers1

1

[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
    }
}
rebello95
  • 8,486
  • 5
  • 44
  • 65
tomsoft
  • 4,448
  • 5
  • 28
  • 35
  • 2
    Pulling the call to [NSNull null] out of the loop and stashing it in a local variable will be even faster. – Catfish_Man Oct 17 '14 at 16:17
  • yes, that was also my thinking but I am expecting the compiler to do it, so not 100% sure, and to lazy to do the test – tomsoft Oct 17 '14 at 16:18
  • 2
    The compiler generally can't cache the results of method calls for you the way it can for functions. You might modify at runtime which method is called (via swizzling or dynamic dispatch for instance). While we know that `null` returns a singleton, it's hard (impossible) for the compiler to prove that. – Rob Napier Oct 17 '14 at 16:23
  • yup. ObjC method calls are essentially full optimization barriers. – Catfish_Man Oct 17 '14 at 18:23