昨天抽空用Swift写了个LRU算法,最后执行1百万数据效率一点都不好,一直都找不到效率慢的原因!早上刚到公司抽空用Objecttive-C和Swift写了个差不多思想的代码(线程安全字典
),对比了下两种语言的效率,你猜怎么着?看结果吧!!!
测试环境:iPhone 5S、16G
测试方法:执行1000000(1百万
)次set
测试结果:柱子越矮越好
测试代码:
Swift版本:
// 被测试类
class ThreadSafeDictionary {
var spinLock:OSSpinLock = OS_SPINLOCK_INIT
var buffer:Dictionary<String,AnyObject> = Dictionary()
static let sharedInstance = ThreadSafeDictionary()
private init(){
}
internal func safeSetObject(object:AnyObject?,forKey:String?) {
if (nil == forKey || nil == object) {
return
}
OSSpinLockLock(&spinLock)
buffer[forKey!] = object
OSSpinLockUnlock(&spinLock)
}
internal func safeGetObject(forKey:String?) -> AnyObject? {
if (nil == forKey) {
return nil
}
var value:AnyObject?
OSSpinLockLock(&spinLock)
value = buffer[forKey!]
OSSpinLockUnlock(&spinLock)
return value
}
}
// 测试代码
let ITERATOR = 1000000 // 1百万
let keys:NSMutableArray = NSMutableArray()
let values:NSMutableArray = NSMutableArray()
for (var i = 0; i < ITERATOR; i++) {
keys.addObject("\(i)")
values.addObject("simple value"+"\(i)")
}
let then = CFAbsoluteTimeGetCurrent()
for (var i = 0; i < ITERATOR; i++) {
ThreadSafeDictionary.sharedInstance.safeSetObject(values[i], forKey: keys[i] as? String)
}
let now = CFAbsoluteTimeGetCurrent();
print("\(now-then)秒")
Objective-C版本:
// 被测试类
#import <Foundation/Foundation.h>
@interface ThreadSafeDictionary : NSObject
+ (instancetype)sharedInstance;
- (void)safeSetObject:(id)object forKey:(NSString*)key;
- (id)safeGetForKey:(NSString*)key;
@end
#import "ThreadSafeDictionary.h"
#import <libkern/OSAtomic.h>
@implementation ThreadSafeDictionary
{
OSSpinLock spinLock;
NSMutableDictionary *buffer;
}
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
static ThreadSafeDictionary *instance;
dispatch_once(&onceToken, ^{
instance = [[ThreadSafeDictionary alloc] init];
});
return instance;
}
- (instancetype)init {
if ((self = [super init])) {
spinLock = OS_SPINLOCK_INIT;
buffer = [NSMutableDictionary dictionaryWithCapacity:50];
}
return self;
}
- (void)safeSetObject:(id)object forKey:(NSString*)key {
if (!object || !key) {
return;
}
OSSpinLockLock(&spinLock);
buffer[key] = object;
OSSpinLockUnlock(&spinLock);
}
- (id)safeGetForKey:(NSString*)key {
if (!key) {
return nil;
}
id value = nil;
OSSpinLockLock(&spinLock);
value = buffer[key];
OSSpinLockUnlock(&spinLock);
return value;
}
@end
// 测试代码
#define ITERATOR 1000000 // 1百万
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
for (NSInteger i = 0; i < ITERATOR; i++) {
[keys addObject:[NSString stringWithFormat:@"%ld",i]];
[values addObject:[NSString stringWithFormat:@"simple value%ld",i]];
}
CFAbsoluteTime then = CFAbsoluteTimeGetCurrent();
@autoreleasepool {
for (NSInteger i = 0; i < ITERATOR; ++i) {
[[ThreadSafeDictionary sharedInstance] safeSetObject:values[i] forKey:keys[i]];
}
}
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
printf("%f秒\n",now-then);