This is supposed to be an optimization that makes your code run faster, at a price that is less readable and therefore likely to contain errors. In your case, I do not quite understand what the code is doing, but obviously there is an error. And there is a good chance that the compiler is smart enough to do what you are trying to do.
In general, the rule: only speed optimization after you have measured the code speed and found that it is too slow. If it is fast enough so that you do not measure speed, then it is fast enough. Then measure before and after making the changes and use your changes only if the speed increases and the code still works correctly.
Instead of using optimizations that reduce the quality of the code, you should find places in your code where you do something in an unnecessarily complicated way and make things simpler and more efficient in this way. Removing unnecessary complications, as a rule, makes your code more correct, more convenient and faster.
source share