Ruby symbols are not garbage collected!? Then, isn't it better to use a String?

前端 未结 3 1310
一个人的身影
一个人的身影 2021-02-14 14:14

If you create 10,000 strings in a loop, a lot of garbage collection has to take place which uses up a lot of resources.

If you do the same thing with symbols, you create

3条回答
  •  别跟我提以往
    2021-02-14 15:00

    If you are using Ruby 2.2.0 or later, it should usually be OK to dynamically create a lot of symbols, because they will be garbage collected according to the Ruby 2.2.0-preview1 announcement, which has a link to more details about the new symbol GC. However, if you pass your dynamic symbols to some kind of code that converts it to an ID (an internal Ruby implementation concept used in the C source code), then in that case it will get pinned and never get garbage collected. I'm not sure how commonly that happens.

    When deciding whether to use symbols or strings you should consider:

    • Symbols cannot be changed after they are created.
    • Symbols do not have a lot of the methods that strings have, like start_with?
    • Symbols can very efficiently be compared to eachother for equality.
    • Symbols are supposed to represent the name of something according to the Symbol docs. I wouldn't use them to store anything that couldn't be considered a name.

提交回复
热议问题