我对使用本地Swift数组和字符串与Objective-C可变数组和NSString进行了一些排序函数测试。
该函数对1000个字符串进行排序,执行了约一百万次字符串比较并打乱了数组。
结果如下:
Objective-C(使用原始整数和布尔值):0.32秒
Objective-C(使用NSNumber的整数和布尔值):0.45秒
调试模式下的Swift:13秒 :)
优化级别为(最快[-O])的Swift:1.32秒
优化级别为(最快,未经检查的[-Ofast])的Swift:0.67秒
似乎在最快模式下,Swift已经接近Objective-C的速度,但仍不如苹果所声称的那么快。
这是我使用的排序代码:
Swift:
var strFile = String.stringWithContentsOfFile("1000strings.txt", encoding: NSUTF8StringEncoding, error: nil)
var strings:String[] = strFile!.componentsSeparatedByString("\n")
var startDate = NSDate()
var shouldLoopAgain = true
var numberOfLoops = 0
while shouldLoopAgain {
shouldLoopAgain = false
++numberOfLoops
for var i = 0; i < strings.count-1; ++i {
if (strings[i] > strings[i+1]) {
let temp = strings[i]
strings[i] = strings[i+1]
strings[i+1] = temp;
if !shouldLoopAgain {
shouldLoopAgain = true
}
}
}
}
var time = NSDate().timeIntervalSinceDate(startDate)
Objective C 中的原始布尔值和整数
NSMutableArray *strings = [NSMutableArray arrayWithArray:[strFile componentsSeparatedByString:@"\n"]];
NSDate *startDate = [NSDate date];
BOOL shouldLoopAgain = YES;
int numberOfLoops = 0;
while (shouldLoopAgain) {
shouldLoopAgain = NO;
++numberOfLoops;
for (int i = 0; i < strings.count-1; ++i) {
if ([strings[i] compare:strings[i+1]] == NSOrderedDescending) {
NSString *temp = strings[i];
strings[i] = strings[i+1];
strings[i+1] = temp;
if (!shouldLoopAgain) {
shouldLoopAgain = YES;
}
}
}
}
NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:startDate];
使用NSNumber处理Objective C中的布尔值和整数
NSDate *startDate = [NSDate date];
NSNumber *shouldLoopAgain = @YES;
NSNumber *numberOfLoops = @(0);
while ([shouldLoopAgain boolValue]) {
shouldLoopAgain = @NO;
numberOfLoops = @([numberOfLoops intValue]+1);
for (NSNumber *i = 0; [i intValue] < strings.count-1; i = @([i intValue]+1)) {
if ([strings[[i intValue]] compare:strings[[i intValue]+1]] == NSOrderedDescending) {
NSString *temp = strings[[i intValue]];
strings[[i intValue]] = strings[[i intValue]+1];
strings[[i intValue]+1] = temp;
if (![shouldLoopAgain boolValue]) {
shouldLoopAgain = @YES;
}
}
}
}
NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:startDate];