loading...

Frozen Strings In Ruby

jwesorick profile image Jake Wesorick Originally published at jake.wesorick.dev ・1 min read

If you're using RuboCop you've probably seen "Missing magic comment # frozen_string_literal: true" at some point at the top of your ruby files. What does that mean? Why should I care?

First, let's talk about frozen strings in Ruby. Strings by default in Ruby are not frozen. This means that when you create a string variable it creates a new space in memory for it.

def get_object_id
  s = "dev.to"
  s.object_id
end

puts get_object_id # 70280383232240
puts get_object_id # 70280382873060 

Ruby gives us a .freeze method to freeze the string. Once it's frozen Ruby can optimize how it runs your code by not creating new space in memory.

def get_object_id
  s = "dev.to".freeze
  s.object_id
end

puts get_object_id # 70280387170560
puts get_object_id # 70280387170560 

Great! So I guess I'll just add .freeze to every string in my code now???? You could but that's where # frozen_string_literal: true comes in. Adding that magic comment to the top of your file lets Ruby know that you want all string literals in the file to be frozen.

Great! So I guess I'll just add # frozen_string_literal: true to the top of all my code???? Maybe! The one gotcha you need to look out for is if you do need to modify your string, but it's frozen, Ruby will throw an exception.

Remembering to freeze strings in your code when you can is a small amount of overhead that can have a big payoff on the performance of your app.

Discussion

pic
Editor guide