Skip to content

Instantly share code, notes, and snippets.

@eregon
Created August 3, 2020 11:10
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 eregon/32f4119b7796ec7a6243c68990949597 to your computer and use it in GitHub Desktop.
Save eregon/32f4119b7796ec7a6243c68990949597 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
$VERBOSE = true
# initialized
class A
def initialize
@c = @d = @e = @f = @g = @h = nil
end
def b
@c || @d || @e || @f || @g || @h
end
end
# not initialized
class B
def initialize
# nothing
end
def b
@c || @d || @e || @f || @g || @h
end
def expected_uninitialized_instance_variable?(iv)
true
end
end
AI = A.new
BI = B.new
Benchmark.ips do |x|
x.iterations = 2
x.report('initialized') { AI.b }
x.report('uninitialized') { BI.b }
x.compare!
end
$ ruby bench_ivar_warn.rb
Warming up --------------------------------------
initialized 1.484M i/100ms
uninitialized 223.758k i/100ms
initialized 1.435M i/100ms
uninitialized 224.504k i/100ms
Calculating -------------------------------------
initialized 14.718M (± 1.6%) i/s - 74.597M in 5.069779s
uninitialized 2.234M (± 0.6%) i/s - 11.225M in 5.023918s
initialized 14.755M (± 1.5%) i/s - 74.597M in 5.057123s
uninitialized 2.227M (± 1.8%) i/s - 11.225M in 5.041341s
Comparison:
initialized: 14754531.3 i/s
uninitialized: 2227414.1 i/s - 6.62x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment