set_cache_size(size)
Sets the maximum size of the in-memory cache in bytes. 🧠
This method allows you to dynamically adjust the memory ceiling for the cache at any point during your application's runtime. You can increase the limit to improve performance by keeping more objects in memory, or decrease it to reduce the process's memory footprint.
If the new size is smaller than the current cache usage, dbzero will automatically evict objects until the new, lower limit is met.
Parameters
- size (
int): The desired maximum size for the cache, specified in bytes.
Returns
This method does not return any value.
Examples
Setting an initial cache size
You can set the cache size right after initialization to control memory usage from the start.
import dbzero as db0
# Initialize dbzero (details omitted)
# db0.init(...)
# Set the cache size to 256 MiB
db0.set_cache_size(256 * 1024 * 1024) Adjusting cache size at runtime
It's also possible to change the cache size on the fly in response to application needs. For instance, you might reduce it after a memory-intensive operation is complete.
import dbzero as db0
# Assume dbzero is initialized and populated with objects
print(f"Initial cache stats: {db0.get_cache_stats()}")
# Create some objects to fill the cache
my_list = db0.list()
for i in range(1000):
my_list.append(b'X' * 1024) # Add 1MB of data
print(f"Cache stats after population: {db0.get_cache_stats()}")
# Now, reduce the cache size to 512 KiB
# This will force dbzero to evict most of the recently added objects.
db0.set_cache_size(512 * 1024)
print(f"Cache stats after downsizing: {db0.get_cache_stats()}")
# The new cache size and capacity will be close to the new 512 KiB limit.