Skip to content

Commit fb190b5

Browse files
nateberkopecJuanitoFatas
authored andcommitted
Clarify Proc.call vs yield, add explanation
The main cost in Proc.call over yield comes from the block argument, not Proc#call.
1 parent 21540c1 commit fb190b5

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

README.md

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -733,23 +733,29 @@ Comparison:
733733
Block: 47914.3 i/s - 1.14x slower
734734
```
735735

736-
##### `Proc#call` vs `yield` [code](code/proc-and-block/proc-call-vs-yield.rb)
736+
##### `Proc#call` and block arguments vs `yield`[code](code/proc-and-block/proc-call-vs-yield.rb)
737+
738+
[In MRI Ruby, block arguments are converted to Procs, which incurs a heap allocation](https://www.omniref.com/ruby/2.2.0/symbols/Proc/yield?#annotation=4087638&line=711).
737739

738740
```
739-
$ ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin13]
741+
$ ruby -v code/proc-and-block/proc-call-vs-yield.rb
742+
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]
740743
Calculating -------------------------------------
741-
block.call 55.809k i/100ms
742-
block + yield 56.025k i/100ms
743-
yield 89.387k i/100ms
744+
block.call 41.978k i/100ms
745+
block + yield 42.674k i/100ms
746+
block argument 41.722k i/100ms
747+
yield 62.681k i/100ms
744748
-------------------------------------------------
745-
block.call 1.069M (±21.2%) i/s - 4.967M
746-
block + yield 1.172M (±16.8%) i/s - 5.715M
747-
yield 4.087M (±11.0%) i/s - 20.201M
749+
block.call 842.581k (±12.5%) i/s - 4.114M
750+
block + yield 941.468k (±11.7%) i/s - 4.651M
751+
block argument 1.043M (± 7.1%) i/s - 5.215M
752+
yield 3.828M (±11.3%) i/s - 18.930M
748753
749754
Comparison:
750-
yield: 4087005.2 i/s
751-
block + yield: 1171912.2 i/s - 3.49x slower
752-
block.call: 1068741.4 i/s - 3.82x slower
755+
yield: 3828436.1 i/s
756+
block argument: 1042509.6 i/s - 3.67x slower
757+
block + yield: 941467.7 i/s - 4.07x slower
758+
block.call: 842581.2 i/s - 4.54x slower
753759
```
754760

755761

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,18 @@ def slow2 &block
88
yield
99
end
1010

11+
def slow3 &block
12+
13+
end
14+
1115
def fast
1216
yield
1317
end
1418

1519
Benchmark.ips do |x|
1620
x.report('block.call') { slow { 1 + 1 } }
1721
x.report('block + yield') { slow2 { 1 + 1 } }
22+
x.report('block argument') { slow3 { 1 + 1 } }
1823
x.report('yield') { fast { 1 + 1 } }
1924
x.compare!
2025
end

0 commit comments

Comments
 (0)