Strings vs Symbols in Ruby

August 15, 2016   

Symbols can be really confusing when you first use Ruby - what are the differences between Strings and Symbols?

Symbols are Faster

Why are symbols faster?

Consider the following:


string_1 = "Hello"
string_2 = "Hello"

Even if it has the same value, we are creating a new string. In other words, in the above example, we have manufactured two strings with the value of "Hello".


string_1 = "Hello"
string_2 = "Hello"

string_1.object_id
# => 70209310447280
string_2.object_id
# => 70209310428440

However, with symbols this isn't the case.


string_1 = :hello
string_2 = :hello

string_1.object_id
# => 1149468
string_2.object_id
# => 1149468

In this case, both :hellos are exactly the same, they are not created twice.

Since there can only be one instance of any symbol, comparison is much faster with symbols compared to strings. With strings, there can be multiple instances of strings with the same value, making the comparison relatively slower.

Moreover, comparison of symbols are a O(1) comparison, so they are super efficient.

When to use symbols

Symbols are immutable. This means that once you create a symbol, you can't change it.

With strings, you have handy methods like upcase! or reverse!, but symbols do not have that capability.

This is why symbols are great for using when you are representing something that shouldn't change.