Rails:cache.fetch vs cache.read/write

dan*_*joo 15 caching ruby-on-rails

是否有任何性能差异

Rails.cache.fetch("key") { Model.all }
Run Code Online (Sandbox Code Playgroud)

models = Rails.cache.read("key")
if models.nil?
    models = Model.all
    Rails.cache.write("key", models)
end
Run Code Online (Sandbox Code Playgroud)

如果我必须猜测,我会说上面的只是另一个的简写.

小智 18

如果你检查源代码,你会注意到fetch除了调用read和之外什么也没做write.

因为它做了一些其他操作(比如检查是否已经给出了一个块等),可以说它fetch更重,但我认为它完全可以忽略不计.

  • 当仅传递单个参数时,将获取键并返回缓存中的值。如果传递了一个块,则**在缓存未命中**的情况下将执行该块。 (2认同)