“一维”散列优势在Perl数组 [英] Advantage of 'one dimensional' hash over array in Perl

查看:141
本文介绍了“一维”散列优势在Perl数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何使用一维散列的效率。(即只按键,没有价值观 - 我们不关心他们无论如何)在一维数组

我想用一个散列用于此目的的主要的原因是这样我就可以使用该功能的存在,看看一个'入门'已经存在。哈希也大不复制钥匙吧?使用数组,我需要设置我的grep参与其中,我带领相信自己的检查会比较慢。

这散列/阵列将被通过某些操作迭代。

我很想听听提前在这个任何见解,并感谢!


解决方案

  $存在哈希{$}键

是一个很好的,短前pression,清晰和易于使用。显然

  !! grep的{$ _ $ EQ键} @array

是不是很短,但

  $键~~ @array#智能匹配

更短。如此以来5.10,它就像语法的容易测试的智能匹配的存在

因此​​,从数组和哈希之间的性能差异猜测,我可以想像,智能匹配将执行更快的少数商品列表,但哈希会的目前的优于数组查找了大名单的项目。

不过,您应该基准性能反正。


这是为什么。草莓perl的,甚至有一个列表大小1,哈希查找优于字符串匹配:

  array_lookup 577701 /秒 -  -46%
hash_lookup 1068376 / s的85% -

随着2项列表中的:

  array_lookup 464684 /秒 -  -57%
hash_lookup 1068376 / s的130% -

和20项:

  array_lookup 181554 /秒 -  -83%
hash_lookup 1068376 / s的488% -

我会使用散列。

I was just wondering about the efficiency of using a one dimensional hash (i.e. only keys, no values - we don't care about them anyway) over a one dimensional array.

The main reason I wanted to use a hash for this purpose is so I can use the exists function to see if an 'entry' already exists. Hashes are also great for not duplicating keys right? With arrays, I would need to set up my own checks involving grep which I'm led to believe would be slower.

This hash/array will then be iterated through for certain operations.

I'd love to hear any insight on this, and thanks in advance!

解决方案

exists $hash{ $key } 

is a nice, short expression, clear and easy to use. Obviously

!!grep { $_ eq $key } @array

Is not quite as short, but

$key ~~ @array # smart match

is even shorter. So since 5.10, it just as syntactically easy to test the smart match as the exists.

So guessing from the performance difference between arrays and hashes, I can imagine that the smart match will perform faster for a small list of items, but the hash will by far outperform the array lookup with a large list of items.

However, you should Benchmark the performance anyway.


And this is why. On Strawberry perl, with even a list size 1, the hash look-up outperforms the string match:

array_lookup  577701/s           --         -46%
hash_lookup  1068376/s          85%           --

With 2 items in the list:

array_lookup  464684/s           --         -57%
hash_lookup  1068376/s         130%           --

And with 20 items:

array_lookup  181554/s           --         -83%
hash_lookup  1068376/s         488%           --

I would use the hash.

这篇关于“一维”散列优势在Perl数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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