Skip to content

Instantly share code, notes, and snippets.

@benaskins
Created April 9, 2009 05:20
Show Gist options
  • Save benaskins/92257 to your computer and use it in GitHub Desktop.
Save benaskins/92257 to your computer and use it in GitHub Desktop.
require 'benchmark'
def v1(value)
value || "-"
end
def v2(object, method)
object && value = object.send(method) ? value : "-"
end
Benchmark.bmbm do |b|
k = Struct.new(:val)
o1 = k.new(20)
o2 = k.new
o3 = nil
n = 1000000
b.report("v1 o1") { n.times { v1(o1.val) } }
b.report("v1 o2") { n.times { v1(o2.val) } }
b.report("v2 o1") { n.times { v2(o1,:val) } }
b.report("v2 o2") { n.times { v2(o2,:val) } }
b.report("v2 o3") { n.times { v2(o3,:val) } }
end
Rehearsal -----------------------------------------
v1 o1 0.400000 0.000000 0.400000 ( 0.532133)
v1 o2 0.490000 0.000000 0.490000 ( 0.904147)
v2 o1 0.570000 0.000000 0.570000 ( 0.989526)
v2 o2 0.670000 0.010000 0.680000 ( 1.149990)
v2 o3 0.340000 0.000000 0.340000 ( 0.540038)
-------------------------------- total: 2.480000sec
user system total real
v1 o1 0.400000 0.000000 0.400000 ( 0.636844)
v1 o2 0.490000 0.000000 0.490000 ( 0.810837)
v2 o1 0.580000 0.000000 0.580000 ( 0.902966)
v2 o2 0.670000 0.000000 0.670000 ( 1.116346)
v2 o3 0.350000 0.010000 0.360000 ( 0.546391)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment