The accepted answer is a good one, but I wanted to add:
function_that_takes_a_lot_of_time_to_compute()
or +[NSString stringWithFormat:]
can have side effects, so even if we knew with 100% certainty that nil_array
was nil
(and we can sometimes know this through static analysis), the program would still have to execute function_that_takes_a_lot_of_time_to_compute()
and +[NSString stringWithFormat:]
to ensure it was behaving as expected.
If a function f()
has no side effects, it is considered "pure." This means that it can take input arguments and can return a value, but it never calls any non-pure functions and never modifies any part of the program or global memory (the memory involved in passing arguments and return values doesn't count here.) The following function, for instance, is "pure":
int munge(float foo, char bar) {
unsigned short quux = bar << 4;
return foo + quux;
}
Examples of pure functions within the C standard library are memcmp()
and strlen()
.
If and only if a function is known to be pure, the compiler could safely optimize away calls to it, since not calling it would have no effect on the rest of the program. However, GCC is very conservative about doing this, and generally (always?) does it only when a function is marked pure, via the __attribute__((__pure__))
decoration on the function declaration.
If a function is pure, and in addition never dereferences pointers and never accesses any memory outside its stack frame, it can instead be marked __attribute__((__const__))
in GCC, which allows even further static analysis and optimization.