Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created November 15, 2009 03:13
Show Gist options
  • Save jodosha/234950 to your computer and use it in GitHub Desktop.
Save jodosha/234950 to your computer and use it in GitHub Desktop.
Ruby benchmark: !@ivar vs defined? @ivar
#!/usr/bin/env ruby -w
require "benchmark"
TIMES = 10_000_000
class Demo
def initialize
@ivar = nil
end
def check_not_nil
!@ivar
end
def check_defined
defined? @ivar
end
end
demo = Demo.new
Benchmark.bm(30) do |b|
b.report "!@ivar" do
TIMES.times do |i|
demo.check_not_nil
end
end
b.report "defined? @ivar" do
TIMES.times do |i|
demo.check_defined
end
end
end
__END__
user system total real
!@ivar 3.330000 0.000000 3.330000 ( 3.392318)
defined? @ivar 5.530000 0.010000 5.540000 ( 5.550502)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment