If you are interested in micro-optimization, you can play with Godbolt's fantastic Compiler Explorer
For example both gcc -O2
and clang -O2
compile your code into just 2 instructions:
FindingMoves(int): # @FindingMoves(int)
lea eax, [rdi + rdi + 3]
imul eax, eax
ret
You could rewrite the source to make it more readable, but modern compilers already squeeze every bit of performance from it.
I personally would write:
int FindingMoves(int input) {
int x = 2 * (input + 1) + 1;
return x * x;
}
Be aware that optimizing a tiny piece of code like this is not worth it, first get the full program to perform correctly and use an extensive test suite to verify that. Then improve your code to make it more readable, more secure, more reliable, and still fully correct as verified by the test suite.
Then, if measured performance is not satisfactory, write performance tests with benchmark data and use a profiler to identify areas of improvement.
Focussing on optimization too soon is called premature optimization, a condition that causes frustration at many levels.