- 浏览: 328611 次
- 性别:
- 来自: 北京
文章分类
最新评论
这里的Memoization就是将ruby的方法或lambda返回值缓存起来的技术。
缓存方法结果:
举个最简单常用的例子:
vs.
下面代码的好处显而易见,在一次请求中最多只调用一次取session和查db操作。
||=这个操作适用于单行赋值操作。是ruby的惯用法之一,一般情况下ruby的||=就可以解决类似的缓存功能。但是情况并不是那么简单,看下面代码:
连续两次调用该方法:
由于||=操作的特性,这里对nil和false返回就不能做缓存了。。还有一个缺点就是不能缓存带参数的方法。。
更通用的memoization:
用方法名对应的实例变量存储结果集,结果集为ruby的hash,不同的参数对应相应的返回值。
这个实现虽然支持了参数形式,缺点同样是不能缓存nil和false返回值。
继续改造:
嗯,可以缓存nil或false返回值了,也可以支持多参数了。不过如果每个方法里这么写也有点烦躁。。
还好ActiveSupport已经写好了这个扩展,使用起来也很方便:
Memoization类方法也很简单,ruby里类方法只不过是Class的实例,只需打开metaclass:
ActiveSupport::Memoizable的实现方式和上面的思路一样,不过用了很多元编程技巧,使用起来才这么方便。
PS:最近面试总有些面试官喜欢问元编程,问神马是元编程,ruby里怎样元编程。。答案无非是“程序运行时动态改变自身”“method_missing、各种eval、define_method、反射等等”
我觉得还不如找些简单功能说说实现方案/思路来的实在。。
这个memoizable同样都不能正确处理带block参数的方法。因为这个memoization本身就不是万金油,也不能滥用。。特别是当方法参数和返回不是一一映射时,比如这两个方法:
随机数:
与动态数据紧密相关的:
缓存Proc/lambda结果:
Via:《Ruby编程语言》
ruby的Hash是个好东西,可以传递Proc做参数,并且缓存结果。
更多关于Proc memoize的内容见NS的这篇:http://www.iteye.com/topic/406220
缓存方法结果:
举个最简单常用的例子:
class ApplicationController < ActionController::Base def current_user User.find(session[:user_id]) end end
vs.
class ApplicationController < ActionController::Base def current_user @current_user ||= User.find(session[:user_id]) end end
下面代码的好处显而易见,在一次请求中最多只调用一次取session和查db操作。
||=这个操作适用于单行赋值操作。是ruby的惯用法之一,一般情况下ruby的||=就可以解决类似的缓存功能。但是情况并不是那么简单,看下面代码:
def may_i_help_u? @result ||= begin #此处是一个耗时很长的判断。。 puts "我被执行了!" false end end
连续两次调用该方法:
may_i_help_u? #=> 我被执行了!. may_i_help_u? #=> 我被执行了!
由于||=操作的特性,这里对nil和false返回就不能做缓存了。。还有一个缺点就是不能缓存带参数的方法。。
更通用的memoization:
def some_method(*args) @some_method ||= {} @some_method[args] ||= ( #这里要等很久 ) end
用方法名对应的实例变量存储结果集,结果集为ruby的hash,不同的参数对应相应的返回值。
这个实现虽然支持了参数形式,缺点同样是不能缓存nil和false返回值。
继续改造:
def some_method(*args) @some_method ||= {} return @some_method[args] if @some_method.has_key?(args) @some_method[args] = ( #这里要等很久 ) end
嗯,可以缓存nil或false返回值了,也可以支持多参数了。不过如果每个方法里这么写也有点烦躁。。
还好ActiveSupport已经写好了这个扩展,使用起来也很方便:
extend ActiveSupport::Memoizable def zipcode_and_name "#{zipcode} #{name}" end memoize :zipcode_and_name
Memoization类方法也很简单,ruby里类方法只不过是Class的实例,只需打开metaclass:
class << self extend ActiveSupport::Memoizable def a_class_method # some code end memoize :a_class_method end
ActiveSupport::Memoizable的实现方式和上面的思路一样,不过用了很多元编程技巧,使用起来才这么方便。
PS:最近面试总有些面试官喜欢问元编程,问神马是元编程,ruby里怎样元编程。。答案无非是“程序运行时动态改变自身”“method_missing、各种eval、define_method、反射等等”
我觉得还不如找些简单功能说说实现方案/思路来的实在。。
这个memoizable同样都不能正确处理带block参数的方法。因为这个memoization本身就不是万金油,也不能滥用。。特别是当方法参数和返回不是一一映射时,比如这两个方法:
随机数:
def rank(n) rand(n*n) end
与动态数据紧密相关的:
def age today = Date.today today.year - birth_date.year + (today.month - birth_date.month + ((today.day - birth_date.day) < 0 ? -1 : 0) < 0 ? -1 : 0) end
缓存Proc/lambda结果:
Via:《Ruby编程语言》
module Functional def memoize cache = {} lambda {|*args| unless cache.has_key? args cache[args] = self[*args] end cache[args] } end alias +@ memoize end Proc.send(:include, Functional) fac = lambda{|x| return 1 if x == 0; x * fac[x - 1];}.memoize #或fac = +lambda{|x| return 1 if x == 0; x * fac[x - 1];}
ruby的Hash是个好东西,可以传递Proc做参数,并且缓存结果。
引用
Hash 映射和 Proc 映射区别在于: Hash 带有缓存机制,而 Proc 不缓存结果。
更多关于Proc memoize的内容见NS的这篇:http://www.iteye.com/topic/406220
评论
7 楼
orcl_zhang
2010-12-08
activesupport/lib/active_support/memoizable.rb
6 楼
wxz125627771
2010-11-20
ray_linn 写道
=java里方法的cache吧?适用于p=f(x),当x既定时,p不变。
5 楼
ywencn
2010-11-19
Hooopo又调皮了.. 送精华一枚...
4 楼
ray_linn
2010-11-18
=java里方法的cache吧?适用于p=f(x),当x既定时,p不变。
3 楼
sina2009
2010-11-18
收藏起....
2 楼
jinleileiking
2010-11-18
hoooopoooooo 你说的东西,我看不懂!(也没仔细看。。。。)
1 楼
fireflyman
2010-11-15
Hooopo总算复活了
发表评论
-
新博客
2012-04-23 20:47 1578https://db-china.org -
Ruby Verbose Warning Mode
2011-10-16 14:48 2015Ruby在很多方面是一个更优雅的Perl,从Perl社区继承了 ... -
Pattern Match In Ruby
2011-10-07 01:17 1961最近看了一些Erlang,模式匹配是个好东西,简单的sum函数 ... -
Draper: View Models for Rails
2011-10-07 01:19 2226Draper是一个Ruby gem,它让Rails model ... -
Active Record batch processing in parallel processes
2011-10-07 01:20 2219Active Record 提供 find_each来分批处理 ... -
最轻量级的Ruby后台任务
2011-08-04 16:47 3811普通情况下ruby调用系统命令行的过程是堵塞的,无论是用sys ... -
test
2011-07-15 19:59 0test -
fiber
2011-06-17 09:37 0挖坑,待填。。 1.用到fiber.alive?、fiber ... -
Identity Map in Rails3.1
2011-06-12 18:29 2697Identity Map是Rails3.1的又 ... -
xx00
2011-06-06 03:40 0https://github.com/ngmoco/cache ... -
挖坑1
2011-06-06 02:17 0cache money 源码 替换memcache为redis ... -
websocket demo
2011-06-04 20:44 2014地址:https://github.com/hooopo/we ... -
ruby GC
2011-06-02 04:24 0http://blog.csdn.net/lijun84/a ... -
reduce method missing call stack with dynamic define method
2011-04-22 22:54 1546method_missing是ruby里面一个非常cool的h ... -
Autocompete with Trie
2011-04-09 04:04 1618像微薄里面用户输入一 ... -
用imagemagick和tesseract-ocr破解简单验证码
2011-04-09 01:31 18848工具:imagemagick + tesseract-ocr ... -
OAuth gem for rails,支持豆瓣,新浪微薄,腾讯微博,搜狐微博,网易微博
2011-03-26 03:13 4440地址:https://github.com/hooopo/oa ... -
用jmeter模拟amf请求进行压力测试
2010-12-16 16:56 29721.获取amf二进制包: 在本地建立proxy,端口为888 ... -
整理了一下2008-2010的RubyHeroes博客列表
2010-10-07 02:26 2790Bryan Helmkamp(webrat作者)https:/ ... -
长期收藏各种有用gems..
2010-09-26 17:17 267Multipart Body – A gem for work ...
相关推荐
这是本学习SketchUp Ruby的好书,应该也是目前市面上唯一专门讲解SketchUp Ruby的专业书籍。原作者为了更多的Ruby爱好者加入进来,慷慨的分享了全书的PDF电子版。(www.autosketchup.com 官方主页提供下载。没有FQ的...
Data Structures and Algorithms in Ruby 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
Design Patterns in Ruby, Addison-wesley (2008). The Addison-Wesley Professional Ruby Series provides readers with practical, people-oriented, and in-depth information about applying the Ruby platform ...
Data Structures and Algorithms in Ruby 英文azw3 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
ruby面向对象设计 英文版 高清 ruby面向对象设计 英文版 高清
Addison.Wesley.Design.Patterns.in.Ruby.Dec.2007 高清PDF英文版
Refactoring.in.Ruby.pdf
Test Driven Development in Ruby: A Practical Introduction to TDD Using Problem and Solution Domain Analysis by Bala Paranj English | 5 Apr. 2017 | ISBN: 1484226372 | 288 Pages | PDF | 5.32 MB Learn ...
Ruby In a Nutshell
Programming Interview Problems and Algorithms in Ruby by Zachary Paul English | April 17, 2016 | ASIN: B01EGILLLS | 177 Pages The book covers a large number of the most common interview problems, as ...
Build Awesome Command-Line Applications in Ruby
Build.Awesome.Command-Line.Applications.in.Ruby
Design Patterns in Ruby Dec 2007.rar
Refactoring In Ruby 非常好的ruby重构
Like Smalltalk, it is dynamically typed (as opposed to Java or C++), but unlike Smalltalk, Ruby features the same conveniences found in modern scripting languages such as Perl and Python. The ...
Data Structures and Algorithms in Ruby 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
ruby 设计模式,针对ruby语言的特点对设计模式做了很好的阐述
Speak directly to your system. With its simple commands, flags, and ... This book is designed to make any programmer or system administrator more productive in their job. This is updated for Ruby 2.