Computing some parts of a function only the first time it is called? For optimization.
- February 22, 2018
- 2 replies
- 4630 views
Dear friends,
This could be a little academic question 🙂
for optimization purposes, would it be possible to compute some precalculations inside a function only the first time it is called? As an example, the attached generalized interpolation function works fine, but to me it is a pity that the vector "vs" get recalculated anytime it is called. To produce the plot, vs will be calculated hundred of times, all the times identical. Let say that I "know" that vx and vy will remain the same.
I am perfectly aware that I could compute vs "outside" the function, making it a "global variable". But I would like to incapsulate this in the function itself. In good old times 🙂 of FORTRAN programming, there was, I believe to remember, a trick based on a DATA statement that preloaded a variable at compile time. At the first execution of a subroutine one could check if the value was the preloaded one, the subroutine knew it was being called for the first time and could perform any required precalculations and store the results in its own private memory.
Thanks a lot for your insights and hints!
Regards,
Claudio



