Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I save strings returned by NSLocalizedString()?

I'm working on an iPhone app that we're localizing in both English and Japanese for our initial release. We frequently call NSLocalizedString() to load the appropriate localized string for display. Is it generally better to save the localized strings in instance variables for the next time we need them, or am I micro-optimizing here and should I just reload the string each time it's needed?

like image 811
Don McCaughey Avatar asked Mar 01 '09 23:03

Don McCaughey


3 Answers

This is one of those "it depends" answers.

Calling NSLocalizedString involves performing a lookup in the bundle. These lookups are pretty fast but not free. Whether to cache this return value or just have the convenience of calling NSLocalizedString will depend on how it's used.

  1. If you're passing the return to the textfield of something like a UILabel or UITableViewCell then the lookup will only occur when you first set the property.

  2. If you're using it in a drawRect call then the lookup will only happen when your view needs to be repainted which could be often, infrequently, or never.

  3. If your using it in a game UI where the screen is redrawn every frame then for a few UI elements these lookups could be happening hundreds of times each second.

I would say that for something like #3 you should start with caching the results.

For the others, write them in the way that's most convenient and if you have performance issues in your UI use Instruments to narrow down the cause. If it's NSLocalizedString then optimize it accordingly.

like image 126
Andrew Grant Avatar answered Oct 24 '22 00:10

Andrew Grant


Micro-optimizing. First make it work, then make it right, then make it fast. And when you get to step 3, run Shark (or Instruments), then follow its guidance.

like image 28
Peter Hosey Avatar answered Oct 23 '22 23:10

Peter Hosey


I suspect that you don't take too much of a performance hit. NSLocalizedString(key, comment) is a macro that converts to

[[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]

Without benchmarking, I have no idea how expensive this is, but I suspect it's not too bad. My feeling is that this won't be a performance bottleneck for you, but you can always run Shark or Instruments and see for yourself when you run your application on the device.

like image 26
Brad Larson Avatar answered Oct 24 '22 01:10

Brad Larson