Overview
Over time, the storage space used by Realm might become fragmented and take up more space than necessary. To rearrange the internal storage and potentially reduce the file size, the realm file needs to be compacted.
El comportamiento predeterminado de Realm es compactar automáticamente un archivo de reino para evitar que crezca demasiado. Puede usar estrategias de compactación manual cuando la compactación automática no sea suficiente para su caso.
Automatic Compaction
New in version 10.20.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.
Opciones de compactación manual
Manual compaction can be used for applications that require stricter management of file size or that use an older version of the SDK that does not support automatic compaction.
Realm reduce el tamaño del archivo escribiendo una nueva versión (compacta) y reemplazando la original con el nuevo archivo. Por lo tanto, para compactar, se requiere un espacio de almacenamiento libre equivalente al tamaño original del archivo realm.
Puede configurar el reino para compactar automáticamente la base de datos cada vez que se abre un reino, o puede compactar el archivo sin obtener primero una instancia del reino.
Realm Configuration File
Puede configurar Realm para que verifique el archivo de reino cada vez que se abra especificando un ShouldCompactDelegate en la configuración. El siguiente ejemplo de código muestra cómo hacerlo:
config = new RealmConfiguration() { ShouldCompactOnLaunch = (totalBytes, usedBytes) => { /* totalBytes refers to the size of the file on disk in * bytes (data + free space). * usedBytes refers to the number of bytes used by * the realm file */ // Compact if the file is over 100MB in size and less // than 50% 'used' var oneHundredMB = 100 * 1024 * 1024; return (totalBytes > (double)oneHundredMB) && ((double)usedBytes / totalBytes < 0.5); } }; var realm = await Realm.GetInstanceAsync(config);
Si el delegado regresa true -- y el archivo no está en uso: el archivo de reino se compacta antes de hacer que la instancia esté disponible.
Método Realm.Compact()
Como alternativa, puede compactar un archivo de dominio sin obtener primero una instancia del dominio mediante el método Compact(). El siguiente ejemplo muestra cómo hacerlo:
config = new RealmConfiguration("my.realm"); Realm.Compact(config);
El método Compact devolverá verdadero si la operación es exitosa.
Consejos para compactar manualmente un Realm
Manually compacting a realm can be a resource-intensive operation. Your application should not compact every time you open a realm. Instead, try to optimize compacting so your application does it just often enough to prevent the file size from growing too large. If your application runs in a resource-constrained environment, you may want to compact when you reach a certain file size or when the file size negatively impacts performance.
Estas recomendaciones pueden ayudarle a comenzar a optimizar la compactación para su aplicación:
Establezca el tamaño máximo de archivo en un múltiplo del tamaño promedio de su estado de dominio. Si el tamaño promedio de su estado de dominio es de 10 MB, puede establecer el tamaño máximo de archivo en 20 MB o 40 MB, según el uso previsto y las limitaciones del dispositivo.
As a starting point, compact realms when more than 50% of the realm file size is no longer in use. Divide the currently used bytes by the total file size to determine the percentage of space that is currently used. Then, check for that to be less than 50%. This means that greater than 50% of your realm file size is unused space, and it is a good time to compact. After experimentation, you may find a different percentage works best for your application.
These calculations might look like this in your delegate:
// Set a maxFileSize equal to 20MB in bytes var maxFileSize = 20 * 1024 * 1024; /* Check for the realm file size to be greater than the max file size, * or the amount of bytes currently used to be less than 50% of the * total realm file size */ return (totalBytes > (double)maxFileSize) && ((double)usedBytes / totalBytes < 0.5);
Experiment with conditions to find the right balance of how often to compact realm files in your application.