數組是線性結構是容器類型,是一塊連續的內存空間, iOS 中用 NSArray 和 NSMutableArray 集合類型,用來存放對象類型,其中 NSArray是不可變類型, NSMutableArray 是可變類型,能夠對數組中元素進行增刪改查.
本文作者本著學習的態度,決定仿照NSArray和NSMutableArray 自己實現一個數組類型,當然性能可能沒有 NSArray和NSMutableArray 的好,插入100000萬條數據,時間上是 NSMutableArray 的三倍左右 ,當然平時使用過程中很少100000次這樣大的數據往數組里添加,因此性能方面可以忽略.
ArrayList.h 主要方法聲明 完全照搬 NSArray 和 NSMutableArray 的方法名稱
先發下測試結果
dispatch_async(dispatch_get_global_queue(0, 0), ^{ Person *p1 = [[Person alloc] init]; NSMutableArray *array = [NSMutableArray arrayWithCapacity:100000];// ArrayList *array = [ArrayList arrayWithCapacity:100000]; CFAbsoluteTime startTime =CFAbsoluteTimeGetCurrent(); for (int i = 0; i<100000; i++) { [array addObject:p1]; } CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - startTime); CFTimeInterval duration = linkTime * 1000.0f; NSLog(@"Linked in %f ms",duration); [self->_timeArray addObject:@(duration)]; count++; });NSMutableArray 5.081740292635832 msArrayList 16.27591523257168 ms以下是 ArrayList 的具體實現 ,內部是一個 C語言的數組用來存放對象//// ArrayList.m// ArrayList//// Created by dzb on 2018/7/19.// Copyright © 2018 大兵布萊恩特. All rights reserved.//#import "ArrayList.h"static NSInteger const defaultCapacity = 10;typedef void * AnyObject;@interface ArrayList (){ AnyObject *_array; NSInteger _size; NSInteger _capacity;}@end@implementation ArrayList#pragma mark - init- (instancetype)init{ self = [super init]; if (self) { [self resetArray]; } return self;}+ (instancetype)array { return [[ArrayList alloc] initWithCapacity:defaultCapacity];}+ (instancetype)arrayWithCapacity:(NSUInteger)numItems { return [[ArrayList alloc] initWithCapacity:numItems];}- (instancetype)initWithCapacity:(NSUInteger)numItems { _capacity = numItems; _array = calloc(_capacity,sizeof(AnyObject)); _size = 0; return self;}/** 數組重置 */- (void) resetArray { _size = 0; if (_array != NULL) _array[_size] = NULL; free(_array); _capacity = defaultCapacity; _array = calloc(_capacity, sizeof(AnyObject));}#pragma makr - 增加操作- (void)addObject:(id)anObject { [self insertObject:anObject atIndex:_size];}- (void)insertObject:(id)anObject atIndex:(NSUInteger)index { if (!anObject) { @throw [NSException exceptionWithName:@"add object null." reason:@"object must be not null ." userInfo:nil]; return; } ///判越界 if ((index > _size)) { @throw [NSException exceptionWithName:@"Array is out of bounds" reason:@"out of bounds" userInfo:nil]; return; } if (_size == _capacity-1) { ///判斷原來數組是否已經滿了 如果滿了就需要增加數組長度 [self resize:2*_capacity]; } ///交換索引位置 if (self.count > 0 ) { for(NSInteger i = _size - 1 ; i >= index ; i--) _array[i + 1] = _array[i]; } self->_array[index] = (__bridge_retained AnyObject)(anObject); _size++;}#pragma mark - 刪除操作- (void)removeAllObjects { NSInteger i = _size-1; while (_size > 0) { [self removeObjectAtIndex:i]; i--; } [self resetArray];}- (void)removeObjectAtIndex:(NSUInteger)index { ///判斷越界 if ((index > _size)) { @throw [NSException exceptionWithName:@"Array is out of bounds" reason:@"out of bounds" userInfo:nil]; return; } AnyObject object =(_array[index]); CFRelease(object); for(NSInteger i = index + 1 ; i < _size ; i ++) _array[i - 1] = _array[i]; _size--; _array[_size] = NULL; ///對數組空間縮減 if (_size == _capacity/2) { [self resize:_capacity/2]; }}- (void)removeObject:(id)anObject { NSInteger index = [self indexOfObject:anObject]; if (index == NSNotFound) return; [self removeObjectAtIndex:index];}- (void)removeLastObject { if ([self isEmpty]) return; [self removeObjectAtIndex:_size-1];}#pragma mark - 修改操作- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject { if (!anObject) { @throw [NSException exceptionWithName:@"add object null." reason:@"object must be not null ." userInfo:nil]; return; } ///判斷越界 if ((index > _size)) { @throw [NSException exceptionWithName:@"Array is out of bounds" reason:@"out of bounds" userInfo:nil]; return; } _array[index] = (__bridge AnyObject)(anObject);}#pragma mark - 查詢操作- (BOOL) isEmpty { return (self->_size == 0);}- (BOOL) isFull { return (self->_size == self->_capacity-1);}- (id)objectAtIndex:(NSUInteger)index { if ((index > _size)) { @throw [NSException exceptionWithName:@"Array is out of bounds" reason:@"out of bounds" userInfo:nil]; return nil; } if ([self isEmpty]) { return nil; } AnyObject obj = _array[index]; if (obj == NULL) return nil; return (__bridge id)(obj);}- (NSUInteger)indexOfObject:(id)anObject { for (int i = 0; i<_size; i++) { id obj = (__bridge id)(_array[i]); if ([anObject isEqual:obj]) return i; } return NSNotFound;}- (BOOL)containsObject:(id)anObject { for (int i = 0; i<_size; i++) { id obj = (__bridge id)(_array[i]); if ([anObject isEqual:obj]) return YES; } return NO;}- (id)firstObject { if ([self isEmpty]) return nil; return (__bridge id _Nullable)(_array[0]);}- (id)lastObject { if ([self isEmpty]) return nil; return (__bridge id _Nullable)(_array[_size]);}- (NSUInteger)count { return _size;}- (NSString *)description { NSMutableString *string = [NSMutableString stringWithFormat:@"/nArrayList %p : [ /n" ,self]; for (int i = 0; i<_size; i++) { AnyObject obj = _array[i]; [string appendFormat:@"%@",(__bridge id)obj]; if (i<_size-1) { [string appendString:@" , /n"]; } } [string appendString:@"/n]/n"]; return string;}/** 對數組擴容 @param capacity 新的容量 */- (void) resize:(NSInteger)capacity { AnyObject *oldArray = _array; AnyObject *newArray = calloc(capacity, sizeof(AnyObject)); for (int i = 0 ; i<_size; i++) { newArray[i] = oldArray[i]; } _array = newArray; _capacity = capacity; free(oldArray);}- (void)dealloc{ if (_array != NULL) [self removeAllObjects]; free(_array);// NSLog(@"ArrayList dealloc");}@end
經過測試 數組內部會對存入的對象 進行 retain 操作 其引用計數+1 ,當對象從數組中移除的時候 能夠正常的使對象內存引用計數-1,因此不必擔心對象內存管理的問題. 數組默認長度是10 , 如果在開發者不確定數組長度時候 ,其內部可以動態的擴容增加數組長度,當執行 remove 操作時候 也會對數組內部長度 進行相應的縮減
實現了 NSArray 和 NSMutableArray 等常用API,如果不是對性能特別在意的場景下 ,可以使用 ArrayList 來存放一些數據
新聞熱點
疑難解答