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

3

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

My question is whether the same is true for creating hashes:

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

And parameter passing:

@post = Post.find_by(:id => 1)
#em vez de
@post = Post.find_by(id: 1)
    
asked by anonymous 25.04.2014 / 13:41

2 answers

3

Second some You should do this yes .

Symbols are stored internally in a table as unsigned integers, which saves a lot of memory compared to using strings. As a result, the comparison between symbols is much faster.

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

But there are always side effects.

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

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

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

    
25.04.2014 / 16:50
5

There is no difference between

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

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

    
25.04.2014 / 18:13