免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2829 | 回复: 0
打印 上一主题 下一主题

Ruby: 延迟计算与优化 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-02-28 10:38 |只看该作者 |倒序浏览
转:LI Daobing


Ruby: 延迟计算与优化






Ruby 的延迟计算大家已经用得很多了, 下面就是一个范例
  1. class ApplicationController  

  2.   def current_user  

  3.     @current_user || User.where(:id => session[:user_id]).first  

  4.   end

  5. end

  6.    
  7. class FooController < ApplicationController  

  8.   def foo  

  9.     current_user  

  10.     current_user  

  11.   end

  12. end
复制代码
但这个范例有一个问题, 如果 current_user 不存在, 那么每次调用 current_user 时都会额外查询一次数据库, 优化的方式就是用 instance_variable_defined? 先查询一下变量是否已经被定义, 测试范例如下
  1. class A

  2.   def foo  

  3.     puts "  expensive computing"

  4.     nil

  5.   end

  6.    
  7.   def failed_lazy  

  8.     @foo ||= foo  

  9.   end

  10.    
  11.   def successful_lazy  

  12.     return @bar if instance_variable_defined? "@bar"

  13.     @bar = foo  

  14.   end

  15.    
  16.   def test  

  17.     puts "use failed lazy computing"

  18.     (1..10).each {failed_lazy}  

  19.     puts "use successful lazy computing"

  20.     (1..10).each {successful_lazy}  

  21.   end

  22. end

  23.    
  24. A.new.test
复制代码
测试结果如下
  1. use failed lazy computing  
  2. expensive computing  
  3. expensive computing  
  4. expensive computing  
  5. expensive computing  
  6. expensive computing  
  7. expensive computing  
  8. expensive computing  
  9. expensive computing  
  10. expensive computing  
  11. expensive computing
  12. use successful lazy computing  
  13. expensive computing
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP