Javascript:有什么理由在哈希表上使用 2 个单独的数组作为键值对?
我看到一些代码将键值对存储在两个数组中。此存储的唯一目的是使用 2 个数组作为哈希表,1 个数组存储键,其他值。这样做有什么性能优势吗?
这个特定的例子由 2 个字符串数组组成..例如
q[0] = "key" v[0] = "value"
I saw some code which was storing key,value pairs in 2 arrays. The only purpose of this storage was to use the 2 arrays as a hashtable, 1 array stored keys, the other values. Is there any performance advantage to doing this?
This particular example consisted of 2 arrays of strings.. e.g
q[0] = "key" v[0] = "value"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会。散列密钥并不是一个非常昂贵的操作。当然,这并不足以证明让这个示例作为真正的哈希表替代品所需的难看的混乱是合理的。
No. Hashing the key is not a very expensive operation. Certainly not to an extent that justifies the unsightly mess that would be required to make this sample work as a real hashtable substitute.
JavaScript 中的数组几乎都是哈希表,它们的键限制为整数。它们不是“真正的”数组,而是像大多数语言一样通过偏移量(索引)访问的连续内存块。我的猜测是原作者假设 JavaScript 中的数组是按照经典意义上实现的。
因此,这本质上是
q["key"] = "value"
并使 q 成为对象而不是数组的低效两倍。Arrays in JavaScript pretty much are hashtables that limit their keys to being integers. They are not "true" arrays that are contiguous slabs of memory that are accessed by an offset (index) like they are in most languages. My guess is the original author assumed an array in JavaScript is implemented in the classical sense.
So this is essentially twice as inefficient as just doing
q["key"] = "value"
and making q an object instead of an array.我想这可能只是一种偏好,但多年来它一直是惯用语。例如,在 C 中,数组具有类型,并且拥有不同类型的数组(即 array[key0]、array[value0]、array[key1]、array[value1])比简单地拥有不同数组中的键和值。对我来说,将键和值放在同一个数组中将是一场噩梦,因为我总是必须记住将该数组中的任何索引加倍,然后对于该值,将其递增。对于我懒惰的大脑来说太多了。
I suppose it could be be merely a preference, but it's been idiomatic for many years. In C, for example, an array has a type and it's more difficult to have an array of varying types (i.e., array[key0], array[value0], array[key1], array[value1]) than simply to have the keys and values in different arrays. For me, it would be a nightmare having keys and values in the same array because I'd always have to remember to double any index into that array and then, for the value, to increment it. Too much for my lazy brain.