Should I use Symbols in hashes and parameters to optimize memory usage in Ruby?

Asked

Viewed 144 times

3

On this other question here I asked about :symbols and 'strings' and found that the use of :symbols optimizes memory usage by the application.

My question is whether the same goes for hashing:

hash = {:indice => 'valor'}
#em vez de
hash = {indice: 'valor'}

And crossing of parameters:

@post = Post.find_by(:id => 1)
#em vez de
@post = Post.find_by(id: 1)

3 answers

5

There’s no difference between

hash = {:indice => 'valor'}    
hash = {indice: 'valor'}

It’s just "syntax sugar," and it only works from 1.9 up.

3


According to some sources you must do this yes.

The symbols are stored internally in a table as integers without signal, which saves a lot of memory compared to the use of strings. As a result, the comparison between symbols is much faster.

Another advantage is that symbols are immutable, while strings can have content altered and "break" somehow the hash.

But there are always side effects.

One is that the symbols are not collected and will reside "eternally" in the interpreter’s table.

The impact will be small if you use only explicit symbols in the code. However, if you use the function to_sym to get the symbols corresponding to many different strings, especially if these strings have external origin, the use of permanently allocated memory can increase considerably.


Specifically talking about the example of the question, the excerpts hash = {:indice => 'valor'} and hash = {indice: 'valor'} are equivalent, the first was used in Ruby until version 1.8 and the second was introduced in Ruby 1.9.

  • 1

    In the links you passed is different from what I asked. In the links they compare {'a' => 'b'} vs {:a => 'b'} and I want to know about {a: 'b'} vs {:a => 'b'}.

  • @user3153542 Truth. I replied to title question and I didn’t exactly notice your example. I’ve already added the explanation in the answer.

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.