Advantage of 'one dimensional' hash over array in Perl

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!

Answers


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.


Need Your Help

SQL select statement for transforming rows to columns based on their unique values

sql oracle11g pivot

I have the data below in a table named training in an oracle database

How to format data value

linq

I have the following Linq to Sql:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.