Nowadays compilers optimize crazy things. Especially gcc and clang sometime do really crazy transformations.
So, I'm wondering why the following piece of code is not optimized:
#include <stdio.h>
#include <string.h>
int main() {
printf("%d\n", 0);
}
I would expect a heavy-optimizing compiler to generate code equivalent to this:
#include <stdio.h>
#include <string.h>
int main() {
printf("0\n");
}
But gcc and clang don't apply the format at compile-time (see https://godbolt.org/z/Taa44c1n7). Is there a reason why such an optimization is not applied?
I see regularly that some format-arguments are known at compile-time, so I guess it could make sense (especially for floating-point values, because there the formatting is probably relatively expensive).
Suppose that at various spots within a function one has the following four lines:
printf("%d\n", 100);
printf("%d\n", 120);
printf("%d\n", 157);
printf("%d\n", 192);
when compiling for a typical ARM microcontroller, each of those printf call would take eight bytes, and all four function calls would share four bytes that are used to hold a copy of the address of the string, and four bytes for the string itself. The total for code and data would thus be 40 bytes.
If one were to replace that with:
printf("100\n");
printf("120\n");
printf("157\n");
printf("192\n");
then each printf call would only need six bytes of code, but would need to have its own separate five-byte string in memory, along with four bytes to hold the address. The total code plus data requirement would thus increase from 40 bytes to 60. Far from being an optimization, thus would actually increase code space requirement by 50%.
Even if there were only one printf call, the savings would be minuscule. Eight bytes for the original version of the call plus eight bytes of data overhead would be 16 bytes. The second version of the code would require eight bytes of code plus seven bytes of data, for a total of 17 bytes. An optimization which would save a little storage in best case, and cost a lot in scenarios that are hardly implausible isn't really an optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With