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

前端 未结 3 1320
一个人的身影
一个人的身影 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条回答
  •  猫巷女王i
    2021-02-14 15:07

    If you refer to the same symbol in your loop, then it doesn't have to recreate that object everytime i.e.

    while i < 10000
      i += 1
      :im_using_this_symbol_here
    end
    

    Now if you use a string there instead, the string will be recreated 10K times. In general, use symbols in cases where you almost treat the literal like a constant or a key. A very good example for me would be

    link_to "News", :action => 'news'
    

    instead of

    link_to "News", "action" => 'news'
    

    action being re-used over and over again within your application.

提交回复
热议问题