Search code examples
iosobjective-cxcodeplist

Speed up code to run through plist


I'm running through a plist with 4000 words. My code works but it takes a few seconds to run the code. Is there anyway to speed up my code to run through the plist?

NSString *path = [[NSBundle mainBundle] pathForResource:@"myList" ofType:@"plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (NSString *str in array) {
NSLog(@"%@", str);
}

Thanks in advance.


Solution

  • NSLog() is slow. Remove that and just do the work, it'll be faster.

    Here's a test comparison of printing each line versus making a new string by appending to the existing string.

       // create test array
       NSMutableArray * strings = [[NSMutableArray alloc] init];
        for (int i = 0; i < 4000; i++)
        {
            [strings addObject:@"new string"];
        }
    
        // create variables for storing test time. 
        CFTimeInterval startTime, endTime;
    
        // test the NSLog loop
        startTime = CACurrentMediaTime();
        for (NSString * string in strings) {
            NSLog(@"%@", string);
        }
        endTime = CACurrentMediaTime();
        NSLog(@"Total Runtime for NSLog: %g s", endTime - startTime);
    
        // test the comparison loop
        startTime = CACurrentMediaTime();
        for (NSString * string in strings) {
            NSString* newString = [string stringByAppendingString:@"   "];
        }
        endTime = CACurrentMediaTime();
        NSLog(@"Total Runtime for appending: %g s", endTime - startTime);
    

    On my iPhone 6 :

    Total Runtime for NSLog: 0.55105 s

    Total Runtime for appending: 0.00366363 s

    The timing test code was modified from this excellent NSHipster article: http://nshipster.com/benchmarking/