Efficient code or problematic code?


#1

On page 89 the book has a for-loop:

NSUInteger dateCount = [dateList count]; for (int i = 0; i < dateCount; i++){ NSDate *d = [dateList objectAtIndex:i]; NSLog(@"The first date is %@", d); }
I thought I could remove some lines and use:

for (int i = 0; i < [dateList count]; i++){ NSLog(@"The first date is %@", [dateList objectAtIndex:i]); }

The second approach, efficient code or code that has unforeseen consequences?


#2

How about “neither” as an answer?

I suspect that the compiler will optimize the original loop to look like your more efficient version, so there’s probably no space/performance gains to be had.

On the other hand, you’ve certainly saved some typing, and I don’t see any side effects.

In general, whether you should streamline code this way depends on two questions: are you confident that the new version behaves the same as the old, and will others who read/maintain the code understand it? In most cases, the programmer time is far more valuable than the CPU time; we’ve moved well beyond the point where efficiency is paramount, although obviously writing painfully inefficient code isn’t desirable either.


#3

thanks for the reply macintux