1

I have a process that is taking longer than I think it should. When I run Instruments, it shows that the method I use to create a key for an NSDictionary lookup is taking about 25% of the overall time. The end result is, if I can optimize this key generation, I could save several seconds. The string gets generated as follows:

[NSString stringWithFormat:@"%ld_%.0f_%.0f_%d%@", (long)zoomLevel, mapPoint.x, mapPoint.y, dataType, suffix];

I feel that parsing the format string is the pain point here, but I'm not sure how else to smash these variables together to create a key.

EDIT

I need to generate the exact same key when given the exact same inputs. So no UUID, timestamp, etc.

Tim Reddy
  • 4,120
  • 1
  • 34
  • 71
  • Is adding time in miliseconds to your String helpful? So it will be unique – Yusuf K. Mar 16 '16 at 13:24
  • Use `NSUUID`. That's what it's for. – Avi Mar 16 '16 at 13:26
  • do you need to be able to regenerate this key or does it simply need to be unique? what are you using the key for? can you structure the data differently? – Wain Mar 16 '16 at 13:26
  • No ready-for-use solution at hand but check [How to generate a hash code from three longs](http://stackoverflow.com/questions/5730149/how-to-generate-a-hash-code-from-three-longs) and [Mapping two integers to one, in a unique and deterministic way](http://stackoverflow.com/questions/919612/mapping-two-integers-to-one-in-a-unique-and-deterministic-way) and also you may google smth like "hash three numbers". – Stanislav Pankevich Mar 16 '16 at 14:10

1 Answers1

2

You can use sprintf instead of [NSString stringWithFormat:...], which performs much faster.

char cString[256];
sprintf(cString, "%ld_%.0f_%.0f_%d%s", (long)zoomLevel, mapPoint.x, mapPoint.y, dataType, suffix.UTF8String];
NSString *string = [[NSString alloc] initWithUTF8String:cString];

Just be sure that you allocate enough space for your string when declaring your char array.

Vinny Coyne
  • 2,335
  • 13
  • 24