Anonymous Monk,
Unfortunately, you didn't provide the stuff that manipulates $val - part of the "slowness" could be there. When you want to evaluate how a tweak has impacted performance - look into Benchmark. The thing to remember here is to go through many iterations to remove "flukes", vary your data as code behaves differently based off input, and try to test on a system at rest so it won't be influenced by other running programs. There is also Devel::DProf.

You also haven't indicated what $val is. In your comment, you say that it generates 4 arrays. If it is a very large scalar, it may be useful to pass the argument as a reference (see References Tutorial & References quick reference) instead of copying the whole thing which is slow.

Additionally, instead of returning the entire hash, you may just want to return a reference to the hash. That would change the my %hash = build_hash($val); to something like my $hash_ref = build_hash($val); You could also not use a return value at all, but build the hash inside the subroutine:

#!/usr/bin/perl -w use strict; my %hash; my $val = "foo bar"; build_hash(\%hash,$val); sub build_hash { my ($hash_ref, $val) = @_; my @vals = split /\s+/ , $val; foreach (@vals) { $hash_ref->{$_} = 1; } }

I am sure there is more optimization that could be done, but this should be a start. The other answers should become obvious after reading the references tutorials I provided.

Cheers - L~R


In reply to Re: Optimizing the use of hashes in subroutines by Limbic~Region
in thread Optimizing the use of hashes in subroutines by Anonymous Monk

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.