These days it's pretty common to see #freeze used in Ruby code. But it's often not entirely clear WHY freeze is being used. In this post we'll look at the most common reasons a developer might freeze variables. To illustrate each reason, I've excerpted example code from the Rails codebase and other popular open-source projects.

Creating immutable constants

In Ruby, constants are mutable. It's a little confusing, but the code is easy enough to understand. Here, I've created a string constant and am appending another string to it.

MY_CONSTANT = "foo"
MY_CONSTANT << "bar"
puts MY_CONSTANT.inspect # => "foobar"

By using #freeze, I'm able to create a constant that's actually constant. This time, when I attempt to modify the string, I get a RuntimeError.

MY_CONSTANT = "foo".freeze
MY_CONSTANT << "bar" # => RuntimeError: can't modify frozen string

Here' a real-world example of this in the ActionDispatch codebase.  Rails hides sensitive data in logs by replacing it with the text "[FILTERED]". This text is stored in a frozen constant.

module ActionDispatch
  module Http
    class ParameterFilter
      FILTERED = '[FILTERED]'.freeze
      ...

Reducing object allocations

One of the best things you can do to speed up your Ruby app is to decrease the number of objects that are created. One annoying source of object allocations comes from the string literals that are sprinkled throughout most apps.

Every time you do a method call like log("foobar"), you create a new String object. If your code calls a method like this thousands of times per second, that means you're creating (and garbage-collecting) thousands of strings per second. That's a lot of overhead!

Fortunately, Ruby gives us a way out. If we freeze string literals, the Ruby interpreter will only create one String object and will cache it for future use. I've put together a quick benchmark showing the performance of frozen vs. non-frozen string arguments. It shows around a 50% performance increase.

require 'benchmark/ips'

def noop(arg)
end

Benchmark.ips do |x|
  x.report("normal") { noop("foo") }
  x.report("frozen") { noop("foo".freeze)  }
end

# Results with MRI 2.2.2:
# Calculating -------------------------------------
#               normal   152.123k i/100ms
#               frozen   167.474k i/100ms
# -------------------------------------------------
#               normal      6.158M (± 3.3%) i/s -     30.881M
#               frozen      9.312M (± 3.5%) i/s -     46.558M

You can see this in action if you look at the Rails router. Since the router is used for every web page request, it needs to be fast. That means a lot of frozen string literals.

# excerpted from https://github.com/rails/rails/blob/f91439d848b305a9d8f83c10905e5012180ffa28/actionpack/lib/action_dispatch/journey/router/utils.rb#L15
def self.normalize_path(path)
  path = "/#{path}"
  path.squeeze!('/'.freeze)
  path.sub!(%r{/+\Z}, ''.freeze)
  path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
  path = '/' if path == ''.freeze
  path
end

Built-in optimizations in Ruby >= 2.2

Ruby 2.2 and later (MRI) will automatically freeze string literals that are used as hash keys.

user = {"name" => "george"}

# In Ruby >= 2.2
user["name"]

# ...is equivalent to this, in Ruby <= 2.1
user["name".freeze]

And according to Matz, all string literals will be frozen automatically in Ruby 3.

Value objects & functional programming

While Ruby isn't a functional programming language, many Rubyists have begun to see the value of working in a functional style. One of the main tenets of this style is that you should avoid side effects. Objects should never change after they've been initialized.

By calling the freeze method inside the constructor, it's possible to guarantee that an object will never change. Any unintentional side-effects will result in an exception being raised.

class Point
  attr_accessor :x, :y
  def initialize(x, y)
    @x = x
    @y = y
    freeze
  end

  def change
    @x = 3
  end
end

point = Point.new(1,2)
point.change # RuntimeError: can't modify frozen Point