Benchmark to_proc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
class User | |
def initialize(first_name:, last_name:, email:) | |
@first_name, @last_name, @email = first_name, last_name, email | |
end | |
def to_s | |
"#{ @first_name } #{ @last_name } (#{ @email })" | |
end | |
def self.to_proc | |
->(*args){ new(*args) } | |
end | |
end | |
def benchmark(repeat: 500) | |
attrs = { first_name: 'John', last_name: 'Doe', email: 'john@doe.com' } | |
user = User.new(attrs) | |
objects = [user]*2000 | |
strings = objects.map(&:to_s) | |
attrs = [attrs]*2000 | |
Benchmark.bmbm do |x| | |
x.report 'map - explicit block' do | |
repeat.times do | |
objects.map { |user| user.to_s } | |
end | |
end | |
x.report 'map - to_proc' do | |
repeat.times do | |
objects.map(&:to_s) | |
end | |
end | |
x.report 'reduce - explicit block' do | |
repeat.times do | |
strings.reduce { |s, name| s + name } | |
end | |
end | |
x.report 'reduce - to_proc' do | |
repeat.times do | |
strings.reduce(&:+) | |
end | |
end | |
x.report 'custom - explicit block' do | |
repeat.times do | |
attrs.map { |attrs| User.new(attrs) } | |
end | |
end | |
x.report 'custom - to_proc' do | |
repeat.times do | |
attrs.map(&User) | |
end | |
end | |
end | |
end | |
benchmark |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
There doesn't seem to be a significant performance impact when using to_proc. | |
user system total real | |
map - explicit block 0.430000 0.000000 0.430000 ( 0.434834) | |
map - to_proc 0.430000 0.000000 0.430000 ( 0.433493) | |
reduce - explicit block 3.510000 1.740000 5.250000 ( 5.254750) | |
reduce - to_proc 3.480000 1.670000 5.150000 ( 5.152428) | |
custom - explicit block 1.210000 0.000000 1.210000 ( 1.214855) | |
custom - to_proc 1.470000 0.000000 1.470000 ( 1.473100) | |
The difference in the object use happens because of the use of variable arguments, rather than the use of to_proc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment