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.
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.
Compact a Realm¶
- The size of the file on disk
- How much free space the file contains
Compacting cannot occur while a realm is being accessed, regardless of any configuration settings.
Make a Compacted Copy¶
How Compacting Works¶
Realm compacting works by:
- Reading the entire contents of the realm file
- Writing the contents to a new file at a different location
- 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.