Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache results from NSUserDefaults?

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).

like image 553
user1272965 Avatar asked Oct 20 '22 18:10

user1272965


1 Answers

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.

like image 52
matt Avatar answered Oct 30 '22 01:10

matt