I consider myself to be a novice programmer and often find myself asking whether a variable should be a member of a class or be created on the fly within the code it's effecting. Is there a trade off to be made when considering this factor or is it down to preference?
Lets say for instance a have a calculation that is rarely updated with new values but is called far more often than an update would occur. It seems to me it's a waste to redo the calculation every time the function call is made instead of just accessing a already calculated variable that belongs to the class that's only updated when necessary.
> Is there a trade off to be made when considering this factor or is it down to preference?
There are lots of tradeoffs, in pretty much everything you do.
> Lets say for instance a have a calculation that is rarely updated with new values but is called far more often than an update would occur.
- How much extra space would you use, storing this data persistently in the class?
- How much actual machine time would you save?
- Would your users actually notice the difference?
Now factor in
- How long is it going to take you to implement and debug this particular change?
- Would the change make the code cleaner and easier to understand?
- Do you have other more important bugs to fix?
- Do you have other more important features that are still to be implemented?
Generally, your first order of business is writing clear code that does what you want. Trying to optimise code before you've finished is likely to be a fool's errand.
The thing about optimisation is that it's a never ending task.
Your customers will care far more about whether the program is late, or doesn't work than they will about the milliseconds of run time that you saved with weeks of your effort.
If considering existing working code without issue, then unless you have an issue, my advice is to leave it alone. It's my view that there are as many bugs introduced by code changes than there was originally....
For new code, then unless you have memory usage constraints, then IMO have it as an updated member variable. But consider each case on it's merits.
is the equation of a simple enough form that you can store what is being computed in vectors and the calculation can adapt (loop) based off the vec size? Eg some form like a*x + b*y + c*z ... where user provides x,y,z or whatever? Then next time you add a variable, it would just work?
@seeplus, thanks for you input :) i have a better understanding of what i should be considering when asking the question.
@jonnin its more a generalized question I realize the more complex the equation the more beneficial it would be to limit the amount of calculations to only what is necessary.
Thanks both for your input i am satisfied with the answers provided. Have a good day!