Answer one: Use Memoize. It's already been tested, so you know it works, and it's a core module, so you know it's there.

Answer two: Use Memoize's method. If you look in the Memoize distribution, there's a test called "speed.t". It works by taking a naive fib implementation, calling it with larger and larger numbers until it takes some given time to execute. Once you've seen it take that amount of time, memoize it, and see if it gets faster. In your own foo() example, break out the $result computation into a separate sub that you can time separately.

Answer three: Pass in a tied scalar as your $arg. Specifically, make a tied scalar that counts the number of times it's been accessed. If you get fewer accesses to it the second time, you know that it was used only to look up the cached result and not to compute the result itself (depending on the algorithm involved, of course). See A heap of medians: efficiency vs. speed for an example. This may not work if your algorithm doesn't actually access the $arg any more than "return $cache{$arg} if exists $cache{$arg}" does. It also might not work if the algorithm copies the scalar once and never uses it again. You might have to overload something so that even the copies exhibit the behavior you want. Implementing and testing this test method might be more trouble than using it to test your foo().

Answer four: Use Memoize.

As an aside, you might find it useful to read When to use Prototypes?


In reply to Re: How to test caching? by kyle
in thread How to test caching? by JavaFan

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.