Search code examples
c++loopsdata-storage

Loops - storing data or recalculating


How much time does saving a value cost me processor-vise? Say i have a calculated value x that i will use 2 times, 5 times, or 20 times.At what point does it get more optimal to save the value calculated instead of recalculating it each time i use it? example:

int a=0,b=-5;
for(int i=0;i<k;++i)
  a+=abs(b);

or

int a=0,b=-5;
int x=abs(b);
for(int i=0;i<k;++i)
  a+=x;

At what k value does the second scenario produce better results? Also, how much is this RAM dependent?


Solution

  • It is almost impossible to provide an answer other than measure in a real scenario. When you cache the data in the code, it may be stored in a register (in the code you provide it will most probably be), or it might be flushed to L1 cache, or L2 cache... depending on what the loop is doing (how much data is it using?). If the value is cached in a register the cost is 0, the farther it is pushed the higher the cost it will take to retrieve the value.

    In general, write code that is easy to read and maintain, then measure the performance of the application, and if that is not good, profile. Find the hotspots, find why they are hotspots and then work from there on. I doubt that caching vs. calculating abs(x) for something as above would ever be a hotspot in a real application. So don't sweat it.