Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Realm Files

Reduce Realm File Size - React Native SDK

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.

Novedad en la versión 11.3.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.

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 reduces the file size by writing a new (compact) version of the file and then replacing the original with the newly-written file. Therefore, to compact, you must have free storage space equivalent to the original realm file size.

Puedes configurar Realm para compactar automáticamente la base de datos cada vez que se abre un realm, o puedes compactar el archivo sin obtener primero una instancia Realm.

Puede configurar Realm para que verifique el archivo de reino cada vez que se abra especificando un FunciónshouldCompact para la configuración. El siguiente ejemplo de código muestra cómo hacerlo:

const shouldCompact = (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 data in the file
// Compact if the file is over 100MB in size and less than 50% 'used'
const oneHundredMB = 100 * 1024 * 1024;
return totalBytes > oneHundredMB && usedBytes / totalBytes < 0.5;
};
const config = { shouldCompact };
let realm = await Realm.open(config);

Alternatively, you can compact a realm file without first obtaining an instance of the realm by calling the compact() method:

const realm = new Realm("my.realm");
realm.compact();

La compact() El método devolverá verdadero si la operación es exitosa.

Puedes guardar una copia compactada (y opcionalmente cifrada) de un dominio en otra ubicación de archivo con el método Realm.writeCopyTo(). El archivo de destino no puede existir previamente.

Importante

Evite llamar a writeCopyTo() dentro de una transacción de escritura. Si se llama dentro de una transacción de escritura, este método copia los datos más recientes. Esto incluye cualquier cambio no confirmado realizado en la transacción antes de llamar a este método.

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.

Estos cálculos podrían parecerse a este:

// Set a maxFileSize equal to 20MB in bytes
const maxFileSize = 20 * 1024 * 1024;
/* Check for the realm file size to be greater than the max file size,
* and 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.

Volver

Encrypt a Realm

En esta página