NSMutableArray vs NSArray which is better

后端 未结 6 1603
再見小時候
再見小時候 2021-02-05 18:11

This is a bit of a silly question, but if I want to add an object to an array I can do it with both NSMutableArray and NSArray, which should I use?

6条回答
  •  无人共我
    2021-02-05 18:41

    This test gives the best answer:

    Method 1:

    NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
    NSMutableArray *mutableItems = [[NSMutableArray alloc] initWithCapacity:1000];
    for (int i = 0; i < 10000; i++) {
        [mutableItems addObject:[NSDate date]];
    }
    NSTimeInterval  end = [NSDate timeIntervalSinceReferenceDate];
    NSLog(@"elapsed time = %g", (end - start) * 1000.0);
    

    Method 2:

    ...
    NSArray *items = [[[NSArray alloc] init] autorelease];
    or (int i = 0; i < 10000; i++) {
        items = [items arrayByAddingObject:[NSDate date]];
    }
    ...
    

    Output:

    Method 1: elapsed time = 0.011135 seconds.    
    Method 2: elapsed time = 9.712520 seconds.
    

提交回复
热议问题