is there any performance difference between
Rails.cache.fetch("key") { Model.all }
and
models = Rails.cache.read("key")
if models.nil?
models = Model.all
Rails.cache.write("key", models)
end
If I must guess, i would say the upper one is just a shorthand for the other one.
The most efficient way to implement low-level caching is using the Rails. cache. fetch method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned.
Rails provides an SQL query cache which is used to cache the results of database queries for the duration of a request. When Rails encounters the same query again within the same request, it uses the cached result set instead of running the query against the database again.
To use Redis as a Rails cache store, use a dedicated Redis cache that's set up as a LRU (Last Recently Used) cache instead of pointing the store at your existing Redis server, to make sure entries are dropped from the store when it reaches its maximum size.
Read Cache – the cache services requests for read I/O only. If the data isn't in the cache, it is read from persistent storage (also known as the backing store). Write Cache – all new data is written to the cache before a subsequent offload to persistent media.
If you check the source code, you'll notice that fetch
does nothing more than call read
and write
.
Since it does some other operations (like checking if a block has been given, etc.) one could say that fetch
is heavier, but I think it's totally negligible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With