1

我通过NSNumber在四个不同的数组中格式化 s 创建一个很长的字符串:

NSString *datos = @"";

for (NSInteger counter = 0; counter < [latOut count]; counter++) {
    datos = [datos stringByAppendingString:[NSString stringWithFormat:@"%.0005f,", [[latOut objectAtIndex:counter] floatValue]]];
    datos = [datos stringByAppendingString:[NSString stringWithFormat:@"%.0005f,", [[lonOut objectAtIndex:counter] floatValue]]];
    datos = [datos stringByAppendingString:[NSString stringWithFormat:@"%ld,", [[tipoOut objectAtIndex:counter] integerValue]]];
    datos = [datos stringByAppendingString:[NSString stringWithFormat:@"%ld\n", [[velocidadOut objectAtIndex:counter] integerValue]]];
}

NSString *curDir = [[NSFileManager defaultManager] currentDirectoryPath];

NSString *path = @"";
path = [path stringByAppendingPathComponent:curDir];
path = [path stringByAppendingPathComponent:@"data.csv"];

// Y luego lo grabamos
[datos writeToFile:path atomically:YES encoding:NSASCIIStringEncoding error:&error];

计数为 18,000 个条目,此循环需要将近 2 分钟才能完成。

我怎样才能让这更快?

4

2 回答 2

4

我在这里看到的主要建议是,由于您经常使用字符串,NSMutableString因此应该使用更有效的方法:

// give a good estimate of final capacity
NSMutableString *datos = [[NSMutableString alloc] initWithCapacity:100000];

for (NSInteger counter = 0; counter < [latOut count]; counter++) {
  [datos appendFormat:@"%.0005f", [[latOut objectAtIndex:counter] floatValue]];
  ...
}

这将避免大量不必要的临时不可变字符串分配。

于 2013-01-24T20:59:15.130 回答
2

您的内存消耗也可能令人震惊。使用可变字符串而不是创建数千个临时字符串:

NSMutableString *datos = [NSMutableString string];

for (NSInteger counter = 0; counter < [latOut count]; counter++) {
    [datos appendFormat:@"%.0005f, %.0005f, %ld, %ld\n", [[latOut objectAtIndex:counter] floatValue], 
                                                         [[lonOut objectAtIndex:counter] floatValue], 
                                                         [[tipoOut objectAtIndex:counter] integerValue], 
                                                         [[velocidadOut objectAtIndex:counter] integerValue]];
}
于 2013-01-24T20:59:21.320 回答