Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Thanks for the reply GrandFather. Not that I didn't believe you, but here's the proof:

#! /usr/bin/perl

use strict;
use warnings;

use File::Spec;
use Data::Dumper;
use Benchmark qw( timethese cmpthese );

my ( undef, undef, $app ) = File::Spec->splitpath( $0 );

open my $DATA, '<', './AXP_FACS.DAT' or die "Error opening file: $!";
my @faclist = (<$DATA>);
chomp @faclist;
close $DATA;

sub grep_by_array {
    my ( $ref ) = @_;
    my @faclist = @$ref;
    my @found;
    foreach my $integer ( 1..5000 ) {
        if ( grep { /\b$integer\b/ } @faclist ) {
            unshift @found, $integer;

    return \@found;


# Convert the array to a hash with the numbers as keys
my %list = map { $_ => 1 } @faclist;

sub grep_by_hash {
    my ( $ref ) = @_;
    my %faclist = %$ref;
    my @found;
    foreach my $integer( 1..5000 ) {
        if ( exists $faclist{$integer} ) {
            unshift @found, $integer;

    return \@found;


# Benchmark the 2 subs
my $r = timethese( 1000, {
        'array' => sub{ grep_by_array(\@faclist) },
        'hash'  => sub{ grep_by_hash(\%list) },

cmpthese( $r );


Benchmark: timing 5000 iterations of array, hash...
     array: 339 wallclock secs (339.02 usr +  0.04 sys = 339.06 CPU) @ 14.75/s (n=5000)
      hash:  8 wallclock secs ( 8.27 usr +  0.00 sys =  8.27 CPU) @ 604.59/s (n=5000)
        Rate array  hash
array 14.7/s    --  -98%
hash   605/s 4000%    --

That's quite an improvement using a hash!
You learn something every day...


In reply to Re^3: Hash checking by njcodewarrior
in thread Hash checking by Anonymous Monk

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (1)
As of 2023-09-28 00:39 GMT
Find Nodes?
    Voting Booth?

    No recent polls found