Trying some iOS programming, and I'm using NSUserDefaults to save a couple NSNumbers my app needs. I am using the typical code to get and set values, e.g.
- (NSNumber *)myUserDefaultNumber {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
return [defaults objectForKey:@"XYZ_MyNumber"];
}
But what I don't know is runtime cost. Can I use this like a regular getter, calling it whenever I need the value like [self myUserDefaultNumber];
, possibly often?
Or is there enough extra cost involved that would motivate me to cache, like:
// setup a property called myUserDefaultNumber, and
- (NSNumber *)myUserDefaultNumber {
if (!_myUserDefaultNumber) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_myUserDefaultNumber = [defaults objectForKey:@"XYZ_MyNumber"];
}
return _myUserDefaultNumber;
}
I know that I shouldn't optimize too early, but its also wrong to do obviously dumb things to begin with. How much worse than a simple memory get is my first approach? (Same question about the setter, which might be even more expensive).
If there's a problem, you're probably looking for it in the wrong place. objectForKey
is low overhead. The high overhead, if there is any, would surely be standardUserDefaults
, because it would at some point have to load the information from disk.
However, you don't know when it does that or how often it does that, so there's really no point caching anything yourself. You just have to assume that, as usual, the runtime knows more than you do. Remember, NSUserDefaults is made to be used - a lot. It is not going to have any "gotchas".
I know that I shouldn't optimize too early, but its also wrong to do obviously dumb things to begin with.
True, but the danger here is that the dumb thing you're doing is to optimize too early. If the docs don't alert you to any possible problems, it's usually safe to assume there won't be any.
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