From: dblack@... Date: 2007-08-07T04:45:37+09:00 Subject: Re: yield or call? Hi -- On Tue, 7 Aug 2007, Phlip wrote: >>> Yes, but not in the helper method. In the code I've shown there's >>> always a block passed to the helper method. Phlip has a point here. >> >> That's very easy to solve: > > What about the two kinds of performance? Programmer performance and > program performance? > > This permits only one (DRY) call to y: > >> y { yield if block_given? } > > So is it performant? Note someone here asserted that yield was faster, > so are these constructions still faster than a brute-force 'block.call > if block' ? > > When I see 'if block' I think of comparing the RVALUE type field to > nil or false. Just a bit mask. Here are some benchmarks, for the two conditionals with and without a block: david-a-blacks-computer:~/hacking dblack$ cat yi.rb require 'benchmark' include Benchmark def x(&b) b.call if b end def y yield if block_given? end n = 1000000 bmbm do |b| b.report("b") { n.times { x { } } } b.report("y") { n.times { y { } } } b.report("b-no block") { n.times { x } } b.report("y-no block") { n.times { y } } end david-a-blacks-computer:~/hacking dblack$ ruby yi.rb Rehearsal ---------------------------------------------- b 3.780000 0.010000 3.790000 ( 3.798711) y 0.700000 0.000000 0.700000 ( 0.695756) b-no block 0.350000 0.000000 0.350000 ( 0.351118) y-no block 0.380000 0.000000 0.380000 ( 0.390713) ------------------------------------- total: 5.220000sec user system total real b 3.810000 0.000000 3.810000 ( 3.846940) y 0.700000 0.010000 0.710000 ( 0.760668) b-no block 0.350000 0.000000 0.350000 ( 0.353762) y-no block 0.390000 0.000000 0.390000 ( 0.390436) So if the test is negative, there's not a huge difference; the difference mainly comes when there is a block. David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)