From: Gavin Kistner Date: 2004-02-20T23:14:54+09:00 Subject: Re: proposal: let kind_of take more arguments Gavin Kistner wrote: > nobu.nokada@softhome.net wrote: > >> unless [Zero, One].any? {|klass| choice.kind_of?(klass)} >> >> Or shorter >> >> unless [Zero, One].any?(&choice.method(:kind_of?) > > > Or, as I noted on the RCR: > > unless ([Zero,One] & choice.class.ancestors).length>0 > For the curious, here's how the three methods above stack up in terms of performance (see below stupid test code that should probably be using Ruby's built-in profiling for the results). The summary is: The third method above is generally faster, unless there's a high probability that a match will be found early on in your test list, in which case the first example above is fastest. -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ instance = ValidForm::Text.new('userName'); testList = [ {:classes => [Array,ValidForm::OptionSet,Module,Method,Fixnum], :name=>'No match is found:'}, {:classes => [Array,ValidForm::OptionSet,Module,Method,Object], :name=>'Match at end of list:'}, {:classes => [Object,Array,ValidForm::OptionSet,Module,Method], :name=>'Match at start of list:'} ] n=50000 puts instance.class.ancestors.join(',') testList.each{ |test| classes=test[:classes] puts test[:name] s1 = Time.now n.times{ (classes & instance.class.ancestors).length>0 } s2 = Time.now printf "Using set intersection: %.2f\n",(s2-s1) s1 = Time.now n.times{ classes.any?{ |k| instance.kind_of?(k) } } s2 = Time.now printf " Using explicit block: %.2f\n",(s2-s1) s1 = Time.now n.times{ classes.any?(&instance.method(:kind_of?)) } s2 = Time.now printf "Passing kind_of? block: %.2f\n",(s2-s1) puts } OUTPUTS ValidForm::Text,ValidForm::Field,Object,Kernel No match is found: Using set intersection: 1.17 Using explicit block: 1.38 Passing kind_of? block: 2.24 Match at end of list: Using set intersection: 1.18 Using explicit block: 1.21 Passing kind_of? block: 2.27 Match at start of list: Using set intersection: 1.19 Using explicit block: 0.46 Passing kind_of? block: 1.26 -- (-, /\ \/ / /\/