I am doing some refactoring work and came across such a piece of code:
bool x = false;
...// maybe some logical work would change the value of x.
if (!x) {
x = true;
}
So, I am curious whether I can do such a replacement:
x = true;
As you can see, I assign x to true directly, which may reduce the number of instructions in the CPU, but I am not sure if there are any hidden dangers.
Any suggestions?
>Solution :
x = true; is clearer than if (!x) { x = true; }.
From performance point of view, former avoids branching, whereas the later doesn’t touch to "cacheline" (in one case).
And compiler might change one to another with as-is rule anyway.