Following the usual short-circuit evaluation question, does short-circuit evaluation work for parameters built and sent against nil objects? Example:
NSMutableArray *nil_array = nil;
....
[nil_array addObject:[NSString stringWithFormat:@"Something big %@",
function_that_takes_a_lot_of_time_to_compute()]];
Is that slow function going to be called or will the whole addObject call be optimized out without processing the parameters?
A message is always dispatched to an object pointer, regardless of whether it points to an object or points to
nil. Additionally, messages are sent in the runtime and therefore the compiler cannot just assumenil_arrayreally isniland optimize it away. What if the initialization did something else, andnil_arrayturns out to be an instance?That means all the expressions you pass as arguments to your methods will be evaluated in order to be passed, so no short-circuiting of any sort happens. Your slow function will be executed, and if it takes a long time it'll affect the performance of your program.
EDIT: I just whipped up a little test case for the heck of it (empty Objective-C command line program). If you run this and observe the debugger console, you'll notice that output from all three calls to
function_that_takes_a_lot_of_time_to_compute()appears (in 5-second intervals), while output from onlyt1's andt3'stest:methods appears — naturally, since these are notnil.main.m
Test.h
Test.m
Output