At work, each new user is assigned a totally random alphanumeric 12-character ID. They’re random instead of sequential because this is what goes into the user’s cookie (and in some cases into URLs) and we didn’t want the IDs to be discoverable. Sometimes we need to do what we call a subscriber load and generate thousands (or sometimes many thousands) of IDs at once. The subload process tends to be very slow, and one of my co-workers was tasked with making it faster. While profiling the code, he discovered that a big time sink was the ID generation procedure. After more research, we discovered that it was written in 2004 and had never been modified after the original checkin. It was hundreds of lines long, used all kinds of global variables (Perl hasn’t had static variables until 5.10), and involved big math with a magic prime number close to 7012. Worse, it was implemented as a hash function. And it was always passed a salt. And that salt was always random.

We replaced it with this code:

my @chars = ('A' .. 'Z', 'a' .. 'z', '0' .. '9');
sub randid {
    $rv = '';
    for my $i (1 .. 12) {
        $rv .= $chars[rand(@chars)];
    }
    return $rv;
}

It used to generate about 100 IDs per second. Now it can do 175,000 per second.