Reputation: 2543
So I am doing long simulations, basically in C++. I have several classes with lots of members and several operations that needs to be done and redone. There are lot of simple task that needs to be done several time.
For big calculations, I have calculated them once and saved it as member. But for simple calculations like addition and subtraction of other members, calculating norm of member array etc., I am confused if saving them also wise decision to boost performance.
For these kind of simple task, is it faster to just calculate each time needed or save the results of calculations as new members and retrieve when needed.
I have many of these simple repetitive calculations so this can make the code really tedious, putting getters, setters for all.
Upvotes: 0
Views: 179
Reputation: 122467
Memoization isnt that tedious. You can get it easily like this:
template <class OUT,class IN>
OUT calc(const IN& x){
// (small) overhead for memoization
static std::map<IN,OUT> memo;
std::map<IN,OUT>::iterator found = memo.find(x);
if (found != memo.end()){ return found->second; }
// (possibly expensive) calculation
double result = doTheCalculation(x); // the actual calculation
memo[x] = result;
return result;
}
When you do this in a clever way, you dont even have to write the memo code for each function where you want to use it but simply reuse it for several functions. Whether it is worth to do this completely depends on your application and the only way to find out is to measure it.
Note that the above might be more efficient by reaplacing the map
with an unordered_map
.
Upvotes: 1