Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Created March 30, 2016 15:26
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 vasilakisfil/bb872e66f4c8870c321c4d22979dfbe6 to your computer and use it in GitHub Desktop.
Save vasilakisfil/bb872e66f4c8870c321c4d22979dfbe6 to your computer and use it in GitHub Desktop.
Have fun with benchmarking in Ruby
require 'benchmark'
@i=0
def undefined_check
return @undefined_check += 2 if defined?(@undefined_check)
return @i += 1
end
@nil = nil
def nil_check
return @nil += 2 unless @nil.nil?
return @i += 1
end
@defined_nil = nil
def defined_nil_check
return @defined_nil += 2 unless defined?(@defined_nil)
return @i += 1
end
@defined = 'defined'
def defined_check
return @defined += 2 unless defined?(@defined)
return @i += 1
end
def no_defined_check
return @i += 1
end
def exception_check
begin
return @undefined += 1
rescue Exception => _
return @i += 1
end
end
n=1600000
Benchmark.bm(25) do |benchmark|
@i=0
benchmark.report("undefined_check") do
n.times { undefined_check }
end
@i=0
benchmark.report("nil_check") do
n.times { nil_check }
end
@i=0
benchmark.report("defined_nil_check") do
n.times { defined_nil_check }
end
@i=0
benchmark.report("defined_check") do
n.times { defined_check }
end
@i=0
benchmark.report("no_defined_check") do
n.times { no_defined_check }
end
@i=0
benchmark.report("exception_check") do
n.times { exception_check }
end
end
# user system total real
#undefined_check 0.200000 0.000000 0.200000 ( 0.194759)
#nil_check 0.170000 0.000000 0.170000 ( 0.176591)
#defined_nil_check 0.200000 0.000000 0.200000 ( 0.196691)
#defined_check 0.210000 0.000000 0.210000 ( 0.209552)
#no_defined_check 0.140000 0.000000 0.140000 ( 0.140443)
#exception_check 4.770000 0.010000 4.780000 ( 4.782087)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment