gpt4 book ai didi

objective-c - 加速循环以创建长字符串

转载 作者:行者123 更新时间:2023-12-03 16:51:17 25 4
gpt4 key购买 nike

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

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 分钟才能完成。

我怎样才能让它更快?

最佳答案

由于您经常使用字符串,因此我在这里看到的主要建议是使用 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]];
...
}

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

关于objective-c - 加速循环以创建长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14510516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com