I have the following code. This is getting calculated in cellForRowAtIndexPath, so I think it could be a little expensive. Is there a better way to calculate a time period?
+(NSString*)toShortTimeIntervalString:(NSString*)sDate
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
[df release];
NSDate* today = [[NSDate alloc] init];
NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
NSTimeInterval interval = [today timeIntervalSinceDate:d];
[today release];
//TODO: added ABS wrapper
double res = 0;
NSString* result;
if(interval > SECONDS_IN_WEEK)
{
res = fabs(interval / SECONDS_IN开发者_运维百科_WEEK);
result = [NSString stringWithFormat:@"%1.0fw ago", res];
}
else if(interval > SECONDS_IN_DAY)
{
res = fabs(interval / SECONDS_IN_DAY);
result = [NSString stringWithFormat:@"%1.0fd ago", res];
}
else if (interval > SECONDS_IN_HOUR){
res = fabs(interval / SECONDS_IN_HOUR);
result = [NSString stringWithFormat:@"%1.0fh ago", res];
}
else if (interval > SECONDS_IN_MIN) {
res = fabs(interval / SECONDS_IN_MIN);
result = [NSString stringWithFormat:@"%1.0fm ago", res];
}
else
{
interval = fabs(interval);
result = [NSString stringWithFormat:@"%1.0fs ago", interval];
}
return result;
}
This doesn't look too bad, and I doubt you'll be seeing too much of a performance hit from it. To make it more efficient, you might consider only creating one NSDataFormatter (saving it in an instance variable or static
variable) and reusing it. Or even better, if you could convert everything to NSDates beforehand, then you wouldn't have to use the formatter every time.
Are you actually seeing any performance issues here, though? Before you try and optimize, you should use Instruments to investigate what's actually taking up time.
Not really, but there are a few categories out there which encapsulate that logic and make it a one line call for you.
Recently I've been in a situation to perform complex calculation (plotting graph for series of years), and I was using NSDate within loops. After analyze with time profiler NSDate, NSDateFormater, NSCalendar was the root cause. I switched to use the C type (time_t + timeinfo) and it drastically improves the speed.
Although they are much faster, they have less functionality, if you need to deal with TimeZone etc, NSDate is probably easier to deal with.
精彩评论