Differences between [NSArray arrayWithArray:] and [NSArray copy]

前端 未结 7 2068
清歌不尽
清歌不尽 2021-02-12 13:50

lately I work much with arrays and I\'m wonder.. what\'s diffrences between those two lines.

NSArray *array = [NSArray arrayWithArray:someArray];
7条回答
  •  我在风中等你
    2021-02-12 14:02

    NSMutableArray *arr = [NSMutableArray array];
    for ( int i = 0; i < 10000; i ++)
    {
        [arr addObject:@(i*1000000ULL)];
    }
    // MARK
    // arr = (id)[NSArray arrayWithArray:arr];
    
    NSTimeInterval t = [NSDate timeIntervalSinceReferenceDate];
    NSArray *res = nil;
    for ( int i = 0; i < 10000; i ++)
    {
        res = [arr copy];
    }
    NSLog(@"time A: %f", [NSDate timeIntervalSinceReferenceDate] - t);
    t = [NSDate timeIntervalSinceReferenceDate];
    for ( int i = 0; i < 10000; i ++)
    {
        res = [NSArray arrayWithArray:arr];
    }
    NSLog(@"time B: %f", [NSDate timeIntervalSinceReferenceDate] - t);
    

    time A: 1.572795, time B: 1.539150, B [NSArray arrayWithArray:] always faster but time difference very small. But if we uncomment "MARK" and get copy from NSArray instead NSMutableArray we will have other runtime A: 0.000473 time B: 1.548400 result: ~3200x times faster

提交回复
热议问题