什么时候最好使用一个数组,而不是在Perl散列? [英] When is it better to use an array instead of a hash in Perl?
问题描述
假设你有一个数组 @a = QW / A B C D /;
和哈希%A =('A'=大于1,'B'=大于1,'C'=> 1,'D'=> 1);
是否有任何情况下创建阵列版本比创建哈希值(当你有其他比对所有的值进行迭代在类似
更好 为(@a){
....
在这种情况下,你将不得不使用键%A
如果您使用的哈希去)?因为测试的特定值是否是在哈希总是比在阵列,正确?
-
 
- 阵列是由数字索引。
- 哈希通过字符串关键字。
-
 
- 到最高指数各项指标在数组中存在。
- 哈希索引稀疏。 (例如,一和c可以不b的存在。)
有很多新兴的性能。首先,
-
 
- 阵列可用于存储有序列表。
- 这将是丑陋的低效使用哈希这种方式。
-
 
- 这是不可能从数组中删除一个元素,除非它是最高的索引元素。
- 您可以从一个有序列表中删除使用实现了一个数组,虽然它是低效率的,除去比第一或最后一个其他元素。
- 这是可能的,从一个哈希删除一个元素,它的效率更高。
Say you have an array @a = qw/ a b c d/;
and a hash %a = ('a' => 1, 'b' => 1, 'c' => 1, 'd' => 1);
Is there any situation where creating the array version is better than creating the hash (other than when you have to iterate over all the values as in something like
for (@a){
....
in which case you would have to use keys %a
if you went with the hash)? Because testing whether a specific value is in a hash is always more efficient than doing so in an array, correct?
- Arrays are indexed by numbers.
- Hashes are keyed by strings.
- All indexes up to the highest index exist in an array.
- Hashes are sparsely indexed. (e.g. "a" and "c" can exist without "b".)
There are many emergent properties. Primarily,
- Arrays can be used to store ordered lists.
- It would be ugly an inefficient to use hashes that way.
- It's not possible to delete an element from an array unless it's the highest indexed element.
- You can delete from an ordered list implemented using an array, though it is inefficient to remove elements other than the first or last.
- It's possible to delete an element from a hash, and it's efficient.
这篇关于什么时候最好使用一个数组,而不是在Perl散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!