为什么没有更多的项目使用 Ruby Symbols 而不是 Strings? [英] Why don't more projects use Ruby Symbols instead of Strings?

查看:38
本文介绍了为什么没有更多的项目使用 Ruby Symbols 而不是 Strings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次开始阅读和学习 ruby​​ 时,我读到了一些关于 ruby​​ 符号对字符串的威力:符号只在内存中存储一​​次,而字符串每个字符串在内存中存储一​​次,即使它们是相同的.

When I first started reading about and learning ruby, I read something about the power of ruby symbols over strings: symbols are stored in memory only once, while strings are stored in memory once per string, even if they are the same.

例如:Rails 的 params 控制器中的哈希有一堆键作为符号:

For instance: Rails' params Hash in the Controller has a bunch of keys as symbols:

params[:id] or
params[:title]...

但其他规模适中的项目,例如 Sinatra 和 Jekyll,则不会这样做:

But other decently sized projects such as Sinatra and Jekyll don't do that:

杰基尔:

post.data["title"] or
post.data["tags"]...

辛纳屈:

params["id"] or
params["title"]...

这使得阅读新代码变得有点棘手,并且很难转移代码并找出使用符号不起作用的原因.这方面的例子还有很多,这有点令人困惑.在这种情况下我们应该还是不应该使用符号?符号的优点是什么?我们应该在这里使用它们吗?

This makes reading new code a little tricky, and makes it hard to transfer code around and to figure out why using symbols isn't working. There are many more examples of this and it's kind of confusing. Should we or shouldn't we be using symbols in this case? What are the advantages of symbols and should we be using them here?

推荐答案

在 ruby​​ 中,在创建 AST 之后,每个符号都表示为一个唯一的整数.使用符号作为哈希键可以使计算速度更快,因为主要操作是比较.

In ruby, after creating the AST, each symbol is represented as a unique integer. Having symbols as hash keys makes the computing a lot faster, as the main operation is comparison.

这篇关于为什么没有更多的项目使用 Ruby Symbols 而不是 Strings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆