Step back.

Ask yourself if your code is actually too slow for your purpose. Only if the answer is "yes", continue.

Before you optimize, benchmark your code. After you did an optimization, benchmark again. Did it get faster? If not, revert.

After each optimization step, ask yourself if the code is now fast enough for your purposes. If yes, stop.

Use a profiler to find the slow parts of your program.


After this section on general optimization technique, I'll now propose a hash-based, on-pass solution. You tell me if it's faster or not. (I can't know, because I don't have real test data; four arrays aren't enough to do any serious performance analysis).

my %uniq; my @new_AOA; foreach my $A (@$AOA) { my $key = $A->[1] . '-' . $A->[3]; push @new_AOA, $A unless $uniq{$key}++ }

Using grep instead of the loop might or might not be faster.

Update: grep version:

my %uniq; my @new_AOA = grep { !( $uniq{$A->[1] . '-' . $A->[3]}++ ) } @AOA;

(Untested, but you get the idea).

And finally it's a good idea to name variables by what they contain, not by the structure of what they contain.

Perl 6 - links to (nearly) everything that is Perl 6.

In reply to Re: Optimize code | remove duplicates from AOA. by moritz
in thread Optimize code | remove duplicates from AOA. by ashish.kvarma

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.