Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: cache.fetch vs cache.read/write

Tags:

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.

like image 642
danijoo Avatar asked Mar 13 '14 12:03

danijoo


People also ask

What is Rails cache fetch?

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.

How does Rails query cache work?

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.

Does Rails cache use Redis?

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.

What is read cache and write cache?

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.


1 Answers

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.

like image 124
beNjiox Avatar answered Oct 26 '22 15:10

beNjiox