IPhone dev - NSTimer precision for time instead of recalculation?

I have a small project that is a timer that counts down to midnight and I was wondering if I should leave it as it is, calculating the time to midnight every second (inside an NSTimer method that is called every 1 second)

NSDate *now = [[NSDate alloc] init];
NSDateComponents *dateComponents = [[self gregorian] components:
                    (NSHourCalendarUnit |
                    NSMinuteCalendarUnit |
                    NSSecondCalendarUnit) fromDate:now];
[now release];
NSUInteger hour = 23 - [dateComponents hour];
NSUInteger min = 59 - [dateComponents minute];
NSUInteger sec = 59 - [dateComponents second];

NSString *time = [[NSString alloc] initWithFormat:@"%02d:%02d:%02d",
                  hour, min, sec];
[[self lblCountDown] setText:
 [time stringByReplacingOccurrencesOfString:@"1" withString:@" 1"]];
[time release];

      

or should I just calculate that the first time and then just subtract one second each time each time, since it syncs up to 1 second per call? I'm not worried that it will take more than 1 second, but if the result is the same, then there is no other reason not to optimize. Anyway, should I do this? And why?

Thank.

+2


source to share


2 answers


The statement "no reason not to optimize" is dangerous. You need a reason to optimize, not no reason! This code is a pretty sane little snippet that shouldn't take long.

When it comes to accuracy, the only sane way to keep accurate time is to let the system do it for you, getting "now" is the way to do it. Taking it into our own hands will likely cause the watch to drift in error, perhaps enough to notice, maybe not.



As far as optimization goes, profile it, see how fast it goes, if it sucks, fix it, if not, move on to something more interesting!

+2


source


Premature optimization is always BAD , don't write code today that can't be debugged in a year. Never make an optimization until you:

  • You have a working application.
  • The working application has poor performance.
  • You've made the toolbox to find the real neck.
  • Are you sure you are using the best algorithm.
  • Figured out how to optimize without sacrificing code clarity.


With all that said and done, checking the current time once a second can never degrade your performance. So obviously you haven't even met requirement 2 to apply the optimizations.

+2


source







All Articles