An array would be better suited than a hash since we're dealing with non-negative integer indexes.
Even in this specific case, the difference in either performance or memory is so marginal as to be essentially unmeasurable.
For 1..1000, both take around 1.3 seconds and negligable amounts of memory. Where the original implementation would take months if not years longer than the universe has existed!
But using a hash for caching makes far more sense because of its generality.
Giving up that generality to move from being 15,000,000 1e+196 times faster to being 15,000,001 1e+196 + 1 times faster is simply pointless. To put that into perspective, it means your changes on top of mine will make a difference of approximately:
0.00000000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000999999999999
+999999999999999999999999999999999999999999999999999999999999999999999
+999999999999999999999999999999999999999999999999999999999999999999999
+999999999999999999999999999999999999999999999900000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000009999999999999999999999999999999999
+999999999999999999999999999999999999999999999999999999999999999999999
+999999999999999999999999999999999999999999999999999999999999999999999
+999999999999999999999999000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000
+000000000000000000000000000000000000000000000000000000000000000000000
+0000000000001%
Worth the effort?
Sub calls are expensive in Perl, and there's no need for recursion here, so let's eliminate them:
Again, an utterly pointless exercise.
When performing the range 1 .. 1000, with the cached version the fib function is called 3005 times. That's twice for each iteration from the main loop, leaving 1 recursion per iteration. Compare that to the original implementation that would call fib() ~1e200 times. That's:
100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,00
+0,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
+,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,
+000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
So any additional savings are so utterly marginal as to be completely unmeasurable.
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.
|