Ruby: 延迟计算与优化
转:LI DaobingRuby: 延迟计算与优化
Ruby 的延迟计算大家已经用得很多了, 下面就是一个范例class ApplicationController
def current_user
@current_user || User.where(:id => session[:user_id]).first
end
end
class FooController < ApplicationController
def foo
current_user
current_user
end
end
但这个范例有一个问题, 如果 current_user 不存在, 那么每次调用 current_user 时都会额外查询一次数据库, 优化的方式就是用 instance_variable_defined? 先查询一下变量是否已经被定义, 测试范例如下class A
def foo
puts "expensive computing"
nil
end
def failed_lazy
@foo ||= foo
end
def successful_lazy
return @bar if instance_variable_defined? "@bar"
@bar = foo
end
def test
puts "use failed lazy computing"
(1..10).each {failed_lazy}
puts "use successful lazy computing"
(1..10).each {successful_lazy}
end
end
A.new.test 测试结果如下use failed lazy computing
expensive 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
页:
[1]