perl中哈希和数组谁更快?

来源:百度知道 编辑:UC知道 时间:2024/09/25 14:01:54
perl中哈希和数组谁更快?(在访问随即位置的数据时)
应该是哈希更快,但是我编程看结果是数组快,不知道为什么。附上程序
#this program test the performance of hash and array in the aspect of speed.
#
@array;
%hash;
$number=50000;

$time1=time;
for($i=0;$i<$number;$i++){
$key=int(rand($numner));
$array[$key]=1;
}
$time2=time;
$time=$time2-$time1;
print"array store cost $time\n";

$time1=time;
for($i=0;$i<$number;$i++){
$key=int(rand($number));
$hash{$key}=1;
}
$time2=time;
$time=$time2-$time1;
print"hash store cost $time\n";

$time1=time;
for($i=1;$i<$number;$i++){
$key=int(rand($number));
$array[$key]++;
}
$time2=time;
$time=$time2-$time1;
print"the access of array cost $time\n";

$time1=time;
for($i=1;$i<$number;$i++){
$key=int(rand($number));

呵呵,你这个蛮有意思。

确实是数组快,而且数组所占内存也小。

hash与数组比较优势在于它的key可以是字符,而数组的index只能是数字。但无论是读存速度还是消耗内存,hash都不如数组的。

补充:具体的我也不是很内行。。。不过你的问题可以考虑放到ChinaUnix的perl版去讨论,链接如下:

http://bbs3.chinaunix.net/forumdisplay.php?fid=25

其实哈希底层也是数组,你给哈希结构传递的每个键值最终通过一些列运算(一般来说是位运算)得到一个对应数组索引的无符号整形值。

你所做的测试随机数直接对应数组下标当然比哈希结果返回结果速度更快。

因为哈希结构多了一步哈希运算。