fast-crystal
fast-crystal copied to clipboard
Performance penalty of Ruby's block shortcut
Hello!
In Proc & Block section you've mentioned:
There is a small performance penalty in Ruby for using &:shortcut
But does that really happen to you? I don't remember the details, but I believe the shortcut's performance has been optimized already. Here are some results of mine:
require "benchmark/ips"
Item = Struct.new(:value)
ITEMS = %w[foo bar baz].map(&Item.method(:new))
def method_1
ITEMS.map(&:value)
end
def method_2
ITEMS.map { |i| i.value }
end
Benchmark.ips do |bm|
bm.report("method_1") { method_1 }
bm.report("method_2") { method_2 }
bm.compare!
end
# >> Warming up --------------------------------------
# >> method_1 210.596k i/100ms
# >> method_2 213.856k i/100ms
# >> Calculating -------------------------------------
# >> method_1 3.472M (± 0.1%) i/s - 17.479M in 5.034397s
# >> method_2 3.434M (± 0.1%) i/s - 17.322M in 5.044515s
# >>
# >> Comparison:
# >> method_1: 3472014.9 i/s
# >> method_2: 3433897.9 i/s - 1.01x slower
# >>
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux-gnu]
Yep, I think you right. I was just going directly off of the fast-ruby repo's Readme.md. In my case, the difference is within 2 %. so not worth mentioning anymore, probably.
Thanks for the answer, good to know that.
I;ll keep this open, so I don't forget to update the wording.