in reply to Fastest data structure compare?

The good thing about using stringified representations of hashes for caching purposes, is that it makes each lookup O(1) (with a largish constant).

Whereas, if you used one of the apparently more efficient, short-circuiting concurrent traversal methods, you have to perform that traversal against every other item (hash) in your cache. And that's O(N) (with a smaller constant). The stringified method wins hands down

One tip if you decide to write your own stringifier, (I'd use Storable::freeze() which is generally much faster than any of the to-text serialisers), prefix your stringified hash with the number of keys it contains. There's no point in comparing the whole stringified hashes if they have different numbers of keys.

Update: Actually, you might as well throw the length of the stringified hash up front also. Something like:

use Storable qw[ freeze ]; my %cache; sub memoised { my $href = shift; my $cacheKey = pack 'NN/a*', scalar keys %$href, freeze $href; return $cache{ $cacheKey } if exists $cache{ $cacheKey }; ## calculate value for href return $cache{ $cacheKey } = $value; }

That should short-circuit any hash collision string compares very quickly in all but the most nearly identical cases. Mind you, you'd be devilishly unlucky to have two nearly identical stringified hashes hash to the same bucket.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."