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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With