Search code examples
coptimizationcompilationdecompiling

loop optimization difference for


Is there any difference between these two in terms of efficiency? Is the second more optimized? I compiled the first code, and then I decompiled it, resulting second code.

for (i = 0; i < n; ++i) {
    if (a[i] == x) {
        printf("%d", a[i]);
        return 0;
    }
}
return 1;

i = 0;
while (1) {
    if (n <= i)
        return 1;
    if (a[i] == x)
        break;
    i = i + 1;
}
printf("%d", a[i]);
return 0;

Solution

  • Both code fragments perform the same thing. The main difference is the first is readable and easy to understand and the second is obfuscated and it takes some thinking to figure that it is really equivalent to the first one, quite confusing indeed as many comments confirm.

    It is vain to think in terms of optimisation in these cases, the compiler is likelly to generate equivalent code for both anyway.

    The conclusion is clear:

    • Always write simple and readable code.
    • Inefficient but correct code always beats broken optimized code.
    • Forget about micro-optimisations, compilers are much better at it than humans.
    • Performance is much more a question of algorithmic complexity than code fine tuning.