As soon as you declare a variable you start to manipulate it. My question is on the speed of manipulation, if it even matters.
Lets say you have a variable total, which is the sum of all values in an array. You want to find the average so you will do total / length. Is it faster for you to declare a new value (ie double avg = total / length), or is it faster to do everything “in place” ( total \= length ), this would of course by ignoring the fact that total is a poor variable name for average, but this is simply to get my point across
I suspect as the processor needs to copy the data from RAM to do the calculation in the ALU or even hardwired calculation in the CPU via bit shifting, but I am not really sure how C++ handles memory, and I am curious as to how that works on the back end.
It depends on how often you will use the average. If it is only used a few times then it’s negligible, but if you need to use that average hundreds or thousands of times then it may be “faster” to use a variable as you don’t have to do the calculation all the time. However, the compilers today are very good when it comes to optimizations, so in reality it’s probably not going to matter.
The only to know for sure is to test it, do some profiling and measurements. Something you should always do before thinking about manual optimizations (I doubt calculating averages, or even more complex things, is going to be a bottleneck.)