Skip to content

Commit 5cf5e0f

Browse files
committed
yield vs block.call misleading
What is slower is to bind the block to a variable, not calling it, just try my version and you will see that slow and slow4 are both 4.x slower than yield alone.
1 parent 9f69c99 commit 5cf5e0f

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

README.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -615,19 +615,20 @@ Comparison:
615615
##### `Proc#call` vs `yield` [code](code/proc-and-block/proc-call-vs-yield.rb)
616616

617617
```
618-
$ ruby -v code/proc-and-block/proc-call-vs-yield.rb
619-
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
620-
618+
$ ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin13]
621619
Calculating -------------------------------------
622-
block.call 70.663k i/100ms
623-
yield 125.061k i/100ms
620+
block.call 55.809k i/100ms
621+
block + yield 56.025k i/100ms
622+
yield 89.387k i/100ms
624623
-------------------------------------------------
625-
block.call 1.309M (± 5.7%) i/s - 6.572M
626-
yield 6.103M (± 7.7%) i/s - 30.390M
624+
block.call 1.069M (±21.2%) i/s - 4.967M
625+
block + yield 1.172M (±16.8%) i/s - 5.715M
626+
yield 4.087M (±11.0%) i/s - 20.201M
627627
628628
Comparison:
629-
yield: 6102822.9 i/s
630-
block.call: 1309452.1 i/s - 4.66x slower
629+
yield: 4087005.2 i/s
630+
block + yield: 1171912.2 i/s - 3.49x slower
631+
block.call: 1068741.4 i/s - 3.82x slower
631632
```
632633

633634

code/proc-and-block/proc-call-vs-yield.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@ def slow &block
44
block.call
55
end
66

7+
def slow2 &block
8+
yield
9+
end
10+
711
def fast
812
yield
913
end
1014

1115
Benchmark.ips do |x|
1216
x.report('block.call') { slow { 1 + 1 } }
17+
x.report('block + yield') { slow2 { 1 + 1 } }
1318
x.report('yield') { fast { 1 + 1 } }
1419
x.compare!
1520
end

0 commit comments

Comments
 (0)