Skip to content

Instantly share code, notes, and snippets.

@cintrzyk
Last active April 3, 2018 09:22
Show Gist options
  • Save cintrzyk/c0a034539be034c847bde03d17b8cbff to your computer and use it in GitHub Desktop.
Save cintrzyk/c0a034539be034c847bde03d17b8cbff to your computer and use it in GitHub Desktop.
require 'benchmark'
class Measurement
LEAN_BODY_MASS_PARAM = 0.01 # dummy value
attr_reader :weight
def lean_body_mass
weight * LEAN_BODY_MASS_PARAM unless weight.nil? # returns nil when no weight
end
end
class Calculator
def lean_body_mass
@lean_body_mass ||= measurements.sort_by(&:lean_body_mass).first.lean_body_mass # simple memoization
end
private
def measurements
a = []
1_000.times do
a << Measurement.new
end
a
end
end
calculator = Calculator.new
Benchmark.bm do |bm|
bm.report do
5_000.times { calculator.lean_body_mass } # will sort every single time due to nil assignment!
end
bm.report do
def calculator.lean_body_mass # fix memoization
return @lean_body_mass if instance_variable_defined?(:@lean_body_mass)
@lean_body_mass ||= measurements.sort_by(&:lean_body_mass).first.lean_body_mass # simple memoization
end
5_000.times { calculator.lean_body_mass } # returns correct memoized value
end
end
####################################################################
# user system total real
# 1.760000 0.010000 1.770000 ( 1.776173) memoization with nil
# 0.000000 0.000000 0.000000 ( 0.000581) fixed memoization
####################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment