in reply to Comparing a value to a list of numbers
The hashtable lookup is by far the fastest approach if you can spare the time to build it in the first place. You wouldn't use the hash approach if you are only doing a search one time on the data set. But if you are doing it many times, the hash approach quickly shines.
Other viable approaches include regex alternation, any, and grep. Observe:
#!/usr/bin/env perl use strict; use warnings; use List::Util qw(any); use Benchmark qw(cmpthese); my @numlist = map {int(rand(100_000))} 1..10_000; my %numlist_table; @numlist_table{@numlist} = (); my $numlist_re = do { my $numlist_str = join('|', @numlist); qr/^(?:$numlist_str)$/; }; my $target = 42; sub sgrep { return grep {$target == $_} @numlist; } sub table { return exists $numlist_table{$target}; } sub alternation { return $target =~ m/$numlist_re/; } sub sany { return any {$target == $_} @numlist; } cmpthese(-3, { grep => \&sgrep, table => \&table, alternation => \&alternation, any => \&sany, });
The results:
Rate grep any alternation table grep 4055/s -- -28% -100% -100% any 5641/s 39% -- -100% -100% alternation 3440637/s 84745% 60895% -- -93% table 48177809/s 1187946% 853994% 1300% --
However, if you consider the time it takes to build the alternation regex, and to build the hash, they are less efficient options for small data sets, or for small numbers of lookups. For large datasets with large numbers of lookups, the hash is a good answer (unless memory is tight).
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Comparing a value to a list of numbers
by LanX (Saint) on Jan 29, 2021 at 17:40 UTC | |
|
Re^2: Comparing a value to a list of numbers
by LanX (Saint) on Jan 30, 2021 at 02:30 UTC |