kreynolds
kreynolds

Reputation: 446

In place data manipulation

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.

Upvotes: 0

Views: 86

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409176

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.)

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

Assuming you meant total /= length, you'll only see a difference where it matters (i.e. when you actually need to use both total and avg, in which case you couldn't use the second version anyway).

I'm against using total /= length because total becomes an average and it isn't semantically correct any more.

Upvotes: 2

count0
count0

Reputation: 2621

That depends on what your compiler does once you turn on optimization.

Upvotes: 1

Related Questions