Skip to Content

Mortal and Immortal symbols in Ruby

Posted on

Symbols are unique

A symbol is unique cause only one instance of the Symbol class can be created for a specific symbol in a running program:

:pending.object_id # => 1277788
:pending.object_id # => 1277788

=> :pending is only created once as the two calls :pending.object_id return the same object identifier.

Strings are different :D

'pending'.object_id # => 70324176174080
'pending'.object_id # => 70324176168090

=> Each time we call, ruby creates a new String object.

Symbol since Ruby 2.2

Immortal symbol

Immortal symbols are symbols that’ll never be garbage collected.

They are generated when your code is dynamically modified. For example, when you use define_method, set_instance_variable, const_set.

Mortal symbol

Mortal symbol on the other hand are eligible for garbage collection.

They are created in other cases. For example, use to_sym, symbol literals

=> We should not create immortal symbols from user inputs cause hackers can create multiple symbols -> flooding our app. As immortal symbols are not garbage collected, create a huge amount of them can force your Ruby process to slow down

Reference: https://medium.com/rubycademy/mortal-and-immortal-symbols-in-ruby-35ae4d29248a

comments powered by Disqus