Speed up your Rails app with frozen constants

Ruby on Rails / Refactoring

Let’s consider the very simple ruby method which takes a country code and returns a country name. I’m sure that many of us write similar methods, especially at the beginning of the Ruby journey.

class SampleClass
  def country_name(country_code:)
    mappings = {
      'us' => 'USA',
      'de' => 'Germany'
    }

    mappings[country_code]
  end
end

To make things more readable we can move mappings outside the method. Moving them to the separated method is ok. Moving them to the constant is good. But moving them to the frozen constant is perfect because it saves some memory for us:

class SampleClass
  COUNTRY_CODES_MAPPINGS = {
    'us' => 'USA',
    'de' => 'Germany'
  }.freeze

  def country_name(country_code:)
    COUNTRY_CODES_MAPPINGS[country_code]
  end
end

Without freezing our constant you will be able to change its value but with a frozen constant you can’t do it – you will experience RuntimeError. Generally, freezing also saves memory for us because it reduces memory allocation.

What’s interesting with Ruby 2.2 string literals used in hash keys are automatically frozen.

Special thanks to my workmate, Darek, who showed me this trick.