123iamking 123iamking - 2 months ago 4x
C Question

Should I reduce set variable

I have 2 C++ code:

Code 1: Reduce assign variable

if(health < healthMax) health = healthMax;

Code 2: Not reduce assign variable

health = healthMax;

I don't know how set and get works, but I personally think that set will change/write the data on memory, and get only read memory, so it's best to get and reduce set - that's why I prefer Code 1 more for now. Am I thinking it right?

Thank you for reading :)


No. The assignment will hopefully compile to a move between registers, which is cheaper than a conditional branch.

If health is a global, you might want to manually sink the store to the global out of the loop, but even a store on every iteration isn't too bad. Repeated stores to the same memory location are cheap, because they will hit in L1 cache. You can expect a throughput of ~1 per clock, without hogging memory bandwidth for other cores.

Since you tagged this as assembly, see the tag wiki for links to performance details for that platform, especially Agner Fog's stuff. A lot of the concepts are similar for other architectures.