On Tue, 2007-08-07 at 01:38 +0900, Pit Capitain wrote:
2007/8/6, James Edward Gray II <james@grayproductions.net>:
> On Aug 6, 2007, at 10:39 AM, Phlip wrote:
> > What if the block were optional?
>
> You can use block_given? to find out if a block was provided.
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.
> 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.
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.