Skip to content

Instantly share code, notes, and snippets.

@joel
Created October 24, 2012 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joel/3945822 to your computer and use it in GitHub Desktop.
Save joel/3945822 to your computer and use it in GitHub Desktop.
tap or not tap
#!/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