为什么Rails的`HashWithIndifferentAccess`将键存储为字符串而不是符号? [英] Why does Rails' `HashWithIndifferentAccess` store keys as strings and not symbols?

查看:65
本文介绍了为什么Rails的`HashWithIndifferentAccess`将键存储为字符串而不是符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用enum将数据库中的整数映射到我的ruby代码中的语义值,但是我注意到它使用的键是字符串.当我检查哈希的类型时,我发现它是一个ActiveSupport::HashWithIndifferentAccess,而不是一个标准的Hash,这很有意义,但是引出了一个问题,为什么Rails选择将值存储并比较为字符串而不是符号,内部.

I am using enum to map integers in my database to semantic values in my ruby code, however I noticed that the keys that it uses are strings. When I checked the type of the hash, I discovered that it was an ActiveSupport::HashWithIndifferentAccess, not a standard Hash, which makes sense, but lead to the question of why Rails chose to store and compare the values as strings, not symbols, internally.

文档状态:

当在整个书写界面中用作键时,内部符号会映射到字符串

Internally symbols are mapped to strings when used as keys in the entire writing interface

由于快速比较,通常在哈希中使用符号,但是Rails选择使用字符串代替.他们为什么选择这样做,性能差异有多大?

Symbols are usually used in hashes because of their fast comparison, but Rails has chosen to use strings instead. Why have they chosen to do this, and how significant is the difference in performance?

推荐答案

他们为什么选择这样做

Why have they chosen to do this

ActiveSupport::HashWithIndifferentAccess主要用于处理来自外部的参数.符号存储在ruby堆中,通常,它们永远不会释放回系统.

ActiveSupport::HashWithIndifferentAccess is mainly used to handle parameters coming from outside. Symbols are stored in the ruby heap and in general, they are never released back to the system.

在从外部获取密钥的东西中使用符号作为密钥会导致针对OutOfMemory攻击的漏洞([D]DoS,使用随机生成的参数名称发送查询.)这就是选择字符串AFAIU的原因.要获得100%的保证,请咨询DHH.

Using symbols as keys in something that gets keys from the outside, leads to the vulnerability against OutOfMemory attacks ([D]DoS, sending queries with randomly generated parameters names.) That’s why strings were chosen, AFAIU. For 100% assurance ask DHH.

性能差异有多重要?

how significant is the difference in performance?

使用 Benchmark 来查看.该网站不应该是请为我做基准"网站.

Use Benchmark to check. This site is not supposed to be a "please do benchmarks for me" site.

这篇关于为什么Rails的`HashWithIndifferentAccess`将键存储为字符串而不是符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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