The size of a realm is always larger than the total size of the objects stored within it. This architecture enables some of realm's performance, concurrency, and safety benefits.
Realm writes new data within unused space tracked inside a file. In some situations, unused space may comprise a significant portion of a realm file. Realm's default behavior is to automatically compact a realm to prevent it from growing too large. You can use manual compaction strategies when automatic compaction is not sufficient for your use case.
Automatic Compaction
New in version 0.9.0.
The SDK automatically compacts Realm files in the background by continuously reallocating data within the file and removing unused file space. Automatic compaction is sufficient for minimizing the Realm file size for most applications.
Automatic compaction begins when the size of unused space in the file is more than twice the size of user data in the file. Automatic compaction only takes place when the file is not being accessed.
Estrategias de compactación manuales
Si la compactación automática se considera insuficiente, se puede usar la compactación manual para las aplicaciones que requieren una gestión más estricta del tamaño de los archivos para mejorar el rendimiento. Una aplicación de producción debería implementar la compactación manual para reducir periódicamente el tamaño del archivo Realm si no utiliza la compactación automática.
Compactar un dominio puede ser una operación costosa que puede bloquear el subproceso de la interfaz de usuario. Optimice la compactación para equilibrar la frecuencia con las mejoras de rendimiento. Si su aplicación se ejecuta en un entorno con recursos limitados, puede que le convenga compactar al alcanzar un tamaño de archivo determinado o cuando este afecte negativamente al rendimiento.
Use either of the following two strategies to compact a realm file manually:
Método estático Realm.compact(): Use este método para compactar un reino. Puede usarlo para compactar un reino de sincronización flexible.
Compacto condicional en abierto: utilizar el
shouldCompactCallback()Cuando desee definir una o más condiciones para determinar si se compacta el dominio. Puede comprobar el tamaño de archivo del dominio, el porcentaje de espacio no utilizado u otras condiciones relevantes para sus necesidades de rendimiento o entorno de ejecución.
Método estático Realm.compact()
Puedes compactar un archivo de reino llamando a Realm.compact()Este método toma una configuración como argumento. Al usar este método, el dispositivo debe tener suficiente espacio libre para crear una copia del dominio.
Realm.compact() obtains an instance of the realm, and opens it to trigger any schema version upgrades, file format upgrades, migration and initial data callbacks. Upon successfully opening the realm and performing these operations, this method then compacts the realm.
If successful, a call to Realm.compact() returns true.
No se debe llamar a este método desde dentro de una transacción. Tampoco puedes compactar un realm abierto.
final config = Configuration.local([Car.schema]); final compacted = Realm.compact(config); print( "Successfully compacted the realm: $compacted"); // On success, this prints "true" final realm = Realm(config);
Conditionally Compact on Open
You can define a shouldCompactCallback() as a property of a realm's configuration. You can use this with both local-only and synced realms with the Configuration.local() and Configuration.flexibleSync() methods, respectively.
This callback takes two int values representing the total number of bytes and the used bytes of the realm file on disk. The callback returns a bool. Compaction only occurs if the bool returns true and another process is not currently accessing the realm file.
The most basic usage is to define a file size at which compaction should occur.
final config = Configuration.local([Car.schema], shouldCompactCallback: ((totalSize, usedSize) { // shouldCompactCallback sizes are in bytes. // For convenience, this example defines a const // representing a byte to MB conversion for compaction // at an arbitrary 10MB file size. const tenMB = 10 * 1048576; return totalSize > tenMB; })); final realm = Realm(config);
Puede definir una lógica más compleja si necesita optimizar el rendimiento para diferentes casos de uso. Por ejemplo, podría establecer un umbral de compactación cuando se utiliza un porcentaje determinado del tamaño del archivo.
final config = Configuration.local([Car.schema], shouldCompactCallback: ((totalSize, usedSize) { // Compact if the file is over 10MB in size and less than 50% 'used' const tenMB = 10 * 1048576; return (totalSize > tenMB) && (usedSize.toDouble() / totalSize.toDouble()) < 0.5; })); final realm = Realm(config);