Created
October 24, 2012 12:32
-
-
Save joel/3945822 to your computer and use it in GitHub Desktop.
tap or not tap
This file contains hidden or 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
#!/usr/bin/env ruby | |
require 'benchmark' | |
N = 1000000 | |
class TestingObjectTap | |
def ugly | |
results = {} | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
results | |
end | |
def sexy | |
returning({}) do |results| | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
end | |
end | |
def returning(obj) | |
yield(obj) | |
obj | |
end | |
def w_tap | |
{}.tap do |results| | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
end | |
end | |
end | |
Benchmark.bmbm do |x| | |
object = TestingObjectTap.new | |
x.report('ugly') { N.times { | |
object.ugly | |
} } | |
x.report('sexy') { N.times { | |
object.sexy | |
} } | |
x.report('sexy') { N.times { | |
object.w_tap | |
} } | |
end | |
# user system total real | |
# ugly 2.820000 0.030000 2.850000 ( 3.093643) | |
# sexy 2.910000 0.030000 2.940000 ( 3.229084) | |
# sexy 3.000000 0.040000 3.040000 ( 3.269924) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment