DEV Community

[Comment from a deleted post]
 
philnash profile image
Phil Nash

The benefits are twofold.

Firstly, memory and performance. If you use the magic comment within a file then every time you use a string literal the string will only be created once and in one location in memory. Further use of the string literal will just point to that initial memory location saving the time of creating a new object and the space of allocating new memory.

Secondly, your string literals are now immutable. This can make your programs easier to reason about. There is a good example in this post which asks what is data after this code runs?

data = "hello"
save(data)
puts data
# => ???

With a mutable string, the save method can change the string data and without knowing the implementation of save you cannot know what data will look like afterwards.

If you use the magic comment, or you freeze the string manually (data = "hello".freeze), then there are only two possible outcomes: data will be the same or save will throw a RuntimeError because it tried to change data.

Finally, it is a good idea to start working with frozen string literals because in Ruby 3 this will be the default behaviour. So it's time to get used to this change so you can be ready for Ruby 3.