Navigation

Compact a Realm - iOS SDK

The size of a Realm Database file is always larger than the total size of the objects stored within it. This architecture enables some of realm's great performance, concurrency, and safety benefits.

Tip
See also:

Realm writes new data within unused space tracked inside file. In some situations, unused space may comprise a significant portion of a realm file. If file size grows large enough to negatively impact performance, compact the realm.

Use shouldCompactOnLaunch() (Swift) or shouldCompactOnLaunch (Objective-C) on a realm's configuration object to compact a realm. Specify conditions to execute this method, such as:

  • The size of the file on disk
  • How much free space the file contains
Important
Compacting may not occur

Compacting cannot occur while a realm is being accessed, regardless of any configuration settings.

let config = Realm.Configuration(shouldCompactOnLaunch: { totalBytes, usedBytes in
// totalBytes refers to the size of the file on disk in bytes (data + free space)
// usedBytes refers to the number of bytes used by data in the file
// Compact if the file is over 100MB in size and less than 50% 'used'
let oneHundredMB = 100 * 1024 * 1024
return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
})
do {
// Realm is compacted on the first open if the configuration block conditions were met.
let realm = try Realm(configuration: config)
} catch {
// handle error compacting or opening Realm
}

You can save a compacted (and optionally encrypted) copy of a realm to another file location with the Realm.writeCopy(toFile:encryptionKey:) method. The destination file cannot already exist.

Important

Avoid calling this method within a write transaction. If called within a write transaction, this method copies the absolute latest data. This includes any uncommitted changes you made in the transaction before this method call, which compromises the atomicity of the transaction.

Realm compacting works by:

  1. Reading the entire contents of the realm file
  2. Writing the contents to a new file at a different location
  3. Replacing the original file

If the file contains a lot of data, this can be an expensive operation.

Experiment with conditions to find the right balance of how often to compact a realm file. Because the operation can be expensive, don't compact every time you open a realm. Do compact often enough to prevent the file size from growing too large.

  • Realm Database's architecture enables threading-related benefits, but can result in file size growth.
  • Use compacting to manage file size growth.
  • Define conditions for shouldCompactOnLaunch() to compact a realm.
  • Compacting cannot occur if another process is accessing the realm.
Give Feedback