[Chicago-talk] neat little optimization, take 2

Jim Thomason thomasoniii at gmail.com
Wed Oct 13 14:01:34 CDT 2004


It seems obvious that the point of my original email was lost. let's
try this again.

Last night I came up with a nifty little optimization that provides
speed increases of up around 50% in specialized circumstances. In
practice, I'm consistently seeing a 33% gain.

Basically, it's useful for when you want to use an object as a key
into a hashref. Since perl's hashes only use scalars as keys, objects
are stringified before becoming a hashkey. So your key is the literal
string 'foo=0x132a7' or whatever.

I have a method that looked up a value in a hash based upon the object
passed in. That object had values associated with it. And it was
(relatively) slow. Then it hit me that perl was re-stringifying the
object every time I used it as the hash key.

Solution? I stringified it once at the start.

my $objectkey = '' . $object;

$hash->{$objectkey};

(replacing simply $hash->{$object})

It all works the same way, but only stringifies once. Massive speed
improvements. Of course, take it with a grain of salt, since we're
talking about going from 3,000/sec -> 4,600/sec. It really only seems
useful for methods that are called frequently that each do lots of
lookups using the object as a hashkey in this manner.

But man, if you have a snippet of code like that, it can help.

-Jim....


More information about the Chicago-talk mailing list