Why are symbols not frozen strings?

前端 未结 6 1914
广开言路
广开言路 2021-01-31 17:59

I understand the theoretical difference between Strings and Symbols. I understand that Symbols are meant to represent a concept or a name or an identifier or a label or a key, a

6条回答
  •  生来不讨喜
    2021-01-31 18:27

    I don't know about a full answer, but here's a big part of it:

    One of the reasons that symbols are used for hash keys is that every instance of a given symbol is exact same object. This means :apple.id will always return the same value, even though you're not passing it around. On the other hand, "apple".id will return a different id every time, since a new string object is created.

    That difference is why symbols are recommended for hash keys. No object equivalency test needs to be done when symbols are used. It can be short-circuited directly to object identity.

提交回复
热议问题