Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UserDefaults Is Cached in Memory #17

Open
ahmedk92 opened this issue May 29, 2020 · 0 comments
Open

UserDefaults Is Cached in Memory #17

ahmedk92 opened this issue May 29, 2020 · 0 comments

Comments

@ahmedk92
Copy link
Owner

(Originally published 2020-05-22)

UserDefaults caches its contents in memory, and loads it on application startup even if it's not used. This is vaguely documented.
From the docs:

UserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value.

Let's do an experiment to confirm that.

Let's make a very simple app based on the single view app template.
Before doing anything, let's record how much memory does our app consumes before any UserDefaults-related work.

On the iPhone SE 2 simulator: 8.7 MB.

Good. Let's save 100 MB of data to UserDefaults and see what we get.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UserDefaults.standard.set(Data(repeating: 1, count: 100_000_000), forKey: "data")    
    return true
}

After running that I got: 104 MB.

OK, let's run again removing that code; essentially like our very first run, and see if anything changes.

Now we got: 104 MB.

So, even if we no longer save or read from UserDefaults, just having that data there makes our app consumes what that data worth in memory.

Code for the experiment.

@ahmedk92 ahmedk92 changed the title Userdefaults Is Cached in Memory UserDefaults Is Cached in Memory Jul 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant