in reply to Why is goto &sub slow?

In the spirit of TIMTOWTDI, here's another option for people who are interested:

It's possible to trade space for computational time by "Memoizing" a function. This consists of storing the answers given by a function in a table that is indexed by the function's arguments. People always use the Fibonacci example, in that context the table would look like this:

------------------------- | Argument | Return Value | |----------|-------------- | 1 | 1 | | 2 | 2 | | 3 | 6 | | 4 | 24 | | 5 | 120 | | 6 | 720 | | 7 | 5040 | | 8 | 40320 | | 9 | 272160 | | 10 | 2721600 | ---------- -------------- So that if your program wanted to compute <code>fibonacci(5)
after the fibonacci function had been memoized, your program would do the following: 1. Return the answer defined in the table if it is defined. 2. Otherwise calculate the answer, put it in the symbol table and then return the value. </code> MJD has made a module called Memoize, and it's very easy to use. Just do this:
use Memoize; memoize('fibonacci');

It's not perfect for every problem, for example if the answers for your function are dependent on a non-explicit parameter (the "localtime" function comes to mind), your answers will be a little odd. Also, there may be problems in which the return values are so big that it's more efficient to recompute the answer when you need it than look it up in a large table. The same problem occurs when you never call your function with the same parameters, this will obviously make your program slower.

It may not be exactly what you're talking about, but your thread made me think of it. :)

Replies are listed 'Best First'.
Re: Re: Why is goto &sub slow?
by Ovid (Cardinal) on Mar 29, 2004 at 14:52 UTC

    I assume you realize that you listed a factorial table and not a fibonacci table? :)

    Cheers,
    Ovid

    New address of my CGI Course.

      10+9+8+7+6+5+4+3+2+1 doesn't equal 2721600?

      Only if you are using base 10 math and boring Euclidean geometry. Think outside the box!