Ruby: 延迟计算与优化
生活随笔
收集整理的這篇文章主要介紹了
Ruby: 延迟计算与优化
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Ruby 的延遲計算大家已經(jīng)用得很多了, 下面就是一個范例
class ApplicationControllerdef current_user@current_user ||= User.where(:id => session[:user_id]).firstend endclass FooController < ApplicationControllerdef foocurrent_usercurrent_userend end但這個范例有一個問題, 如果 current_user 不存在, 那么每次調(diào)用 current_user 時都會額外查詢一次數(shù)據(jù)庫, 優(yōu)化的方式就是用 instance_variable_defined? 先查詢一下變量是否已經(jīng)被定義, 測試范例如下
class Adef fooputs " expensive computing"nilenddef failed_lazy@foo ||= fooenddef successful_lazyreturn @bar if instance_variable_defined? "@bar"@bar = fooenddef testputs "use failed lazy computing"(1..10).each {failed_lazy}puts "use successful lazy computing"(1..10).each {successful_lazy}end endA.new.test測試結(jié)果如下
use failed lazy computingexpensive computing
expensive computing
expensive computing
expensive computing
expensive computing
expensive computing
expensive computing
expensive computing
expensive computing
expensive computing
use successful lazy computing
expensive computing
- update1: 第一段的代碼范例有錯誤: "||" 應(yīng)該改為 "||="?
轉(zhuǎn)載于:https://www.cnblogs.com/lidaobing/archive/2011/02/26/optimize-lazy-evaluation-in-ruby.html
總結(jié)
以上是生活随笔為你收集整理的Ruby: 延迟计算与优化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于分布式系统的数据一致性问题(三)
- 下一篇: Oracle学习(五)DBLINK