Performance issue finding weekdays over a given period

Posted by Oysio on Stack Overflow See other posts from Stack Overflow or by Oysio
Published on 2010-05-13T23:15:32Z Indexed on 2010/05/13 23:24 UTC
Read the original article Hit count: 205

Filed under:
|
|
|

I have some methods that return the number of weekdays between two given dates. Since calling these methods become very expensive to call when the two dates lie years apart, I'm wondering how these methods could be refactored in a more efficient way. The returned result is correct but I feel that the iphone processor is struggling to keep up and consequently freezes up the application when I would call these methods over a period of say 10years. Any suggestions ?

    //daysList contains all weekdays that need to be found between the two dates
    -(NSInteger) numberOfWeekdaysFromDaysList:(NSMutableArray*) daysList 
                                              startingFromDate:(NSDate*)startDate 
                                              toDate:(NSDate*)endDate
    {
     NSInteger retNumdays = 0;

     for (Day *dayObject in [daysList objectEnumerator])
     {
      if ([dayObject isChecked])
      {
       retNumdays += [self numberOfWeekday:[dayObject weekdayNr] startingFromDate:startDate toDate:endDate];
      }
     }

     return retNumdays;
    }


    -(NSInteger) numberOfWeekday:(NSInteger)day 
                                 startingFromDate:(NSDate*)startDate 
                                 toDate:(NSDate*)endDate
    {
     NSInteger numWeekdays = 0;
     NSDate *nextDate = startDate;

     NSComparisonResult result = [endDate compare:nextDate];

     //Do while nextDate is in the past
     while (result == NSOrderedDescending || result == NSOrderedSame) 
     {
      if ([NSDate weekdayFromDate:nextDate] == day)
      {
       numWeekdays++; 
      }

      nextDate = [nextDate dateByAddingDays:1];
      result = [endDate compare:nextDate];
     }

     return numWeekdays;
    }

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c