I've been working (for far too long) on a mail-script to deliver to 50,000 users (more added every week). It's got to the point where it's grinding the mail-server, particularly if there are invalid addresses in the list.

It occurred to me that I could optimise this by delivering to the most frequent addresses first: should save on nslookups, and frequently-appearing hostnames are more likely to be valid than the "go@away.no.spam" variety. About 80% of the list should be processed before I run into the single-user hostnames. The most frequently occurring hostname is on the same host as the mailing program, so this 40% of the list should be delivered almost immediately. (BTW, the host doesn't use sendmail - I don't get to choose the MTA.)

Here's the outline of the code I produced, and I'd be grateful for any comments about how I could do this more efficiently. It's not bad atm, sorting the 50,000 addresses in ~ 3 secs, but I'm sure there's another and probably more efficient way to do it.

# unsorted addresses start off in the @addresses array. # sorted ones end up in the @recipients array. foreach my $address (@addresses) { my ($name, $host) = split(/\@/, $address); # various checks on the validity of name and host, snipped push @{$host}, "$name\@$host"; $frequency{$host}++; } foreach my $host (reverse sort { $frequency{$a} <=> $frequency{$b} } k +eys %frequency) { foreach my $address (@{$host}) { push @recipients, $address; } @{$host} = -1; }

So I'm naturally concerned about the wild proliferation of (often one-element) arrays, even though these are exterminated later. TIA.


In reply to Sorting a list by frequency of items by yojimbo

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.