Andrew Johnson
Andrew Johnson

Reputation: 13286

This loop is very slow, I think because I create a lot of intermediate strings. How can I speed it up?

NSArray *splitPoints = [routeGeom componentsSeparatedByString:@"], ["];
routePoints = malloc(sizeof(CLLocationCoordinate2D) * ([splitPoints count] + 1));

int i=0;
NSArray *coords; 
for (NSString* coordStr in splitPoints) {

  coords = [coordStr componentsSeparatedByString:@","];

  routePoints[i].latitude = [[[coords objectAtIndex:0] substringFromIndex:1]floatValue];
  routePoints[i].longitude = [[coords objectAtIndex:1] floatValue];

  i++;

}
[coords release];

NSLog(@"** Time to split the route geometry into structs %f", [NSDate timeIntervalSinceReferenceDate] - start);

Upvotes: 1

Views: 508

Answers (4)

dreamlax
dreamlax

Reputation: 95335

I just thought I'd jump in here and say that your line [coords release] is unnecessary (and wrong). You should remove it to avoid problems in non-GC environments. You do not have to release coords because you did not explicitly create or retain it.

Upvotes: 2

NSResponder
NSResponder

Reputation: 16861

This looks to me like a case where NSScanner would be a win. -componentsSeparatedByString and -substringFromIndex are both going to create heap objects, which is something you don't want to be doing in a tight loop.

Upvotes: 2

Will Hartung
Will Hartung

Reputation: 118611

Consider:

char *buf = [coordStr UTF8String];
sscanf(buf, "%f,%f", &routePoints[i].latitude, routePoints[i].longitude);

Upvotes: 6

Ben Gottlieb
Ben Gottlieb

Reputation: 85532

I would consider using [coordStr UTF8String]'s returned c-string and manually parsing the characters.

Upvotes: 2

Related Questions