另一种速度提升可能吗?

感谢受访者对这个问题的回答( 这个循环很慢,我认为因为我创建了很多中间字符串。我怎样才能加快速度? )我能够将代码加速多个数量级。

我想我可能会做得更好一些。 是否有可能避免在这里创建一堆NSString,而是将大的NSString(routeGeom)拆分成一堆char缓冲区并迭代这些缓冲区?

我从来没有做过任何C编程,所以如果你知道如何完成这项工作,我将不胜感激!

NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate]; NSString *routeGeom = [pieces objectAtIndex:1]; NSArray *splitPoints = [routeGeom componentsSeparatedByString:@"],["]; routePoints = malloc(sizeof(CLLocationCoordinate2D) * ([splitPoints count] + 1)); int i=0; for (NSString* coordStr in splitPoints) { char *buf = [coordStr UTF8String]; sscanf(buf, "%f,%f,", &routePoints[i].latitude, &routePoints[i].longitude); i++; } 

删除realloc,这是一个更好的方法。 你也不应该使用arrayname [index]迭代一个循环。 而是使用指针,即

 int array[5000]; int* intPointer = &array; for(int i=0;i<5000;i++,intPointer++) *intPointer = something 

执行&routePoints[i]强制CPU每个循环多次执行'&routePoints + i * sizeof(CLLocationCoordinate2D)“。

我强烈建议你买一本关于C的书并学习它。 从长远来看,你将受益。

我知道这个答案不能立即帮助你,但是使用一个非常长的字符串并使用C将其分解为更小的字符串实际上是一个非常常见且简单的事情(以非常快速和有效的方式)。

 char *buf = [routeGeom UTF8String]; int bestGuess = 1 << (whatever); routePoints = malloc(sizeof(CLLocationCoordinate2D) * bestGuess); for (int i = 0; buf != NULL; buf = strchr(buf+1,'['), ++i) { if (i >= bestGuess) { bestGuess <<= 1; routePoints = realloc(routePoints, sizeof(CLLocationCoordinate2D) * bestGuess); } sscanf(buf+1, "%f,%f,", &(routePoints + i)->latitude, &(routePoints + i)->longitude); } 

(whatever)选择一个良好的起始值,以便2代表路线中的平均点数。 如果你不能,你可以尝试根据字符串的长度猜测数字。 否则,如果你想要准确,你可以解析字符串两次,先计数,然后创建routePoints ,然后解析数据,在这种情况下你不需要realloc部分。

编辑:

另外一个选项。 这假设CLLocationCoordinate2D只是2个浮点数的结构,其顺序与字符串中的数据相同。

 char *buf = [routeGeom UTF8String]; int bestGuess = 1 << (whatever); float *tmpFloats = (float *)malloc(sizeof(float) * bestGuess); float *index = tmpFloats; for (int i = 0; buf != NULL; buf = strchr(buf+1,'['), ++i, index += 2) { if (i >= bestGuess) { bestGuess <<= 1; tmpFloats = (float *)realloc(tmpFloats, sizeof(float) * bestGuess); } sscanf(buf+1, "%f,%f,", index, index + 1); } CLLocationCoordinate2D *routePoints = (CLLocationCoordinate2D *)tmpFloats; 

你应该真的使用NSScanner来完成这项任务 – 为了实现微小的性能提升,实际上并不值得花时间。