Ruby 性能:多键哈希
假设我有一些查找表,q(w, x, y, z)
,其中各种键组合映射到不同的值;即,q(0, 0, 0, 0) = a,q(0, 0, 0, 1) = b,q(15, 16) , 23, "b") = c.
就效率而言,在 Ruby 中实现此结构的最佳方法是什么?键将动态生成,通常是字符串。我可以想到三种不同的哈希键控方法:
- 使用字符串作为键:
q["a, b, c, d"] = 0
- 使用单个数组作为键:
q[["a", "b", "c", "d"]] = 0
- 使用哈希值的哈希值:
q["a"]["b"]["c" ][“d”] = 0
我目前正在使用方法2,它比我想要的要慢一些。这些键组合是动态生成的 - 如果我使用采用单个字符串的哈希,字符串连接会更快吗?我应该首先从散列的散列开始吗?这种方法会占用更多的内存空间吗?
Suppose I have some lookup table, q(w, x, y, z)
, where various combination of keys map to different values; i.e., q(0, 0, 0, 0) = a
, q(0, 0, 0, 1) = b
, q(15, 16, 23, "b") = c
.
What's the best way to implement this structure in Ruby in terms of efficiency? The keys will be generated dynamically and will generally be strings. I can think of three different keying methods with hashes:
- Use a string as the key:
q["a, b, c, d"] = 0
- Use a single array as the key:
q[["a", "b", "c", "d"]] = 0
- Use a hash of hashes:
q["a"]["b"]["c"]["d"] = 0
I'm currently using method 2, and it's a little slower than I would like. These key combinations are generated dynamically—if I were to use a hash that takes a single string, will string concatenation be faster? Should I have started with a hash of hashes in the first place? Will this method take more space in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会选择像你的#1这样的东西:创建一个字符串,然后将其用作你的地图键。但是,请确保您的“代理哈希键”对于各种值组合来说都是唯一的。在这种情况下,您只需构建一个简单的字符串并需要一个映射。
一般来说,您希望映射键尽可能不可变。 (密钥突变可能会弄乱桌子)。有时在 Ruby 中会很混乱,因为字符串是可变的,但仍然是一个值得实现的目标。
I would opt for something like your #1: create a single string which will then act as your map key. However ensure that your 'surrogate hash key' will be appropriately unique for various combinations of values. In this case you only have to build a simple string and need a single map.
Generally speaking you want map keys to be as immutable as possible. (A key mutating could mess up the table). Sometimes messy in Ruby since strings are mutable but still a worthwhile goal.