Skip to content

βœ… Why when using a frozen string we don't allocate memory?

Benoit Tigeot edited this page Jan 18, 2018 · 1 revision

I use a method because it represents "patterns" we discuss with my team, I try to measure the number of allocations between calling directly string, calling a string set into a constant outside the function and calling a string frozen in a constant outside the function.

require 'memory_profiler'

report_1 = MemoryProfiler.report do
  def get_me_directly
    "hey"
  end
  get_me_directly
end

report_2 = MemoryProfiler.report do
  ST = "yep"
  def get_me_with_constant
    ST
  end
  get_me_with_constant
end

report_3 = MemoryProfiler.report do
  ST_FREEZE = "yop".freeze
  def get_me_with_constant_freeze
    ST_FREEZE
  end
  get_me_with_constant_freeze
end

report_1.pretty_print
# Allocated String Report
# -----------------------------------
#          1  "hey"
#          1  measure_allocation.rb:5
#
#
# Retained String Report
# -----------------------------------

report_2.pretty_print
# Allocated String Report
# -----------------------------------
#          1  "yep"
#          1  measure_allocation.rb:11
#
#
# Retained String Report
# -----------------------------------
#          1  "yep"
#          1  measure_allocation.rb:11

report_3.pretty_print
# Allocated String Report
# -----------------------------------
#
# Retained String Report
# -----------------------------------

As mentionned by Sam Saffron it can happen when :

it was allocated earlier when the ruby code was parsed. You can confirm this by loading a file and putting the load in a mem profiler block.

Check and updated benchmark that doesn't show this weird behavior: https://github.com/benoittgt/understand_ruby_memory/blob/master/memory_freeze_benchmark.rb

Clone this wiki locally