The most effective way to increase dates

I would like to increase the number of days in the cycle so that it 2012-11-10 , 2012-11-11 , 2012-11-12 , ...

What is the most effective way to achieve this?

 NSDate *iterationDate = [NSDate date]; for (int i = 0; i < 100; i++) { NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setYear:0]; [comps setMonth:0]; [comps setWeek:0]; [comps setDay:1]; [comps setHour:0]; [comps setMinute:0]; [comps setSecond:0]; iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0]; } 
+4
source share
2 answers

If you need all the intermediate NSDate s, just get comps out of the loop:

 NSDate *iterationDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setYear:0]; [comps setMonth:0]; [comps setWeek:0]; [comps setDay:1]; [comps setHour:0]; [comps setMinute:0]; [comps setSecond:0]; for (int i = 0; i < 100; i++) { iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0]; } 

You can achieve something similar using the CoreFoundation APIs:

 CFCalendarRef calendar = CFCalendarCreateWithIdentifier(0, kCFGregorianCalendar); CFAbsoluteTime at = CFAbsoluteTimeGetCurrent(); const CFOptionFlags options = 0; for (int i = 0; i < NIter; ++i) { if (0 == CFCalendarAddComponents(calendar, &at, options, "d", 1)) { assert(0 && "uh-oh"); } CFDateRef date = CFDateCreate(0, at); // store result CFRelease(date); } CFRelease(calendar); 

It is measured 33% faster than Foundation. It is even faster if you do not need to create CFDates and just store CFAbsoluteTime values.

+3
source

I think your path is not bad, just do not select the NSDateComponents ( comps ) object every time:

 NSDate *iterationDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:1]; for (int i = 0; i < 100; i++) iterationDate = [currentCalendar dateByAddingComponents:comps toDate:iterationDate options:0]; 

Another way could be (it should be faster, but you need to test ...):

 NSDate *iterationDate = [NSDate date]; int daysToAdd = 1; for (int i = 0; i < 100; i++) iterationDate = [iterationDate addTimeInterval:60*60*24*daysToAdd]; 
+2
source

Source: https://habr.com/ru/post/1445193/


All Articles