This answer on another question says that
array.map(&:to_s)
is faster than
array.map { |n| n.to_s }
In the first example, & turns :to_s into a Proc. The second example uses a block.
Why might a Proc be faster than a block in that benchmark? Is there some optimization that this technique allows the interpreter to do?
As others have been said this is specifically about
Symbol#to_procrather than procs in general and it is almost certainly ruby implementation dependant. BeforeSymbol#to_procwas in ruby itself, the pure ruby implementations of it were definitely slower the the equivalent block.For a real answer you’d want to profile ruby while you’re executing such a benchmark.
My reading of the ruby source code is that when you call
Symbol#to_procthe proc you get is a bit special: The body of the proc is just a C api call (rb_funcall_passing_block), whereas in the other cases it’s actual ruby code which takes a little longer to execute.