This is currently an idea, an idea to optimize the operation of the program. It may not be rigorous. I hope to rewrite the code to achieve optimal performance during the compilation phase. We all know that the most commonly used optimization method is splicing, not fmt.Printf or fmt.Sprintf.
But using fmt.Printf or fmt.Sprintf can achieve extremely high readability. So I was wondering whether it is possible to rewrite fmt.Sprintf into splicing during the compilation phase. E.g
Note that BenchmarkStrconv reports 4 allocations per operation while BenchmarkPrintf reports 2 allocations. Even though BenchmarkStrconv runs faster, for the average program the extra two allocations will take more CPU time over all as the garbage collector has to work harder.
I think that this idea may be beneficial for format strings that contain only %s. I think it is unlikely to be beneficial if any other formatting directives are used.
Apart from not always being faster there are other reasons to avoid this kind of rewrite:
changing the code of fmt package without changing the compiler will result in behaviour that does not align with programmer expectation that changed the fmt code
if someone copies fmt into a new package (e.g. for small changes) there will be a performance loss even while it is potentially the same code being executed (that is why it is prefered for the compiler to match a pattern instead of a specific function)
if one of the called functions panics the stack trace will be different then from then expected from the fmt package.
the behaviour of String methods will too since fmt with recover the panic and print a string for it and the above code does not
In general the rewrite will need to be much more complex and needs to honor Stringer GoStringer and other method invocations on the types/interfaces.
it adds complexity to the compiler while it mostly will only support very narrow use cases (or otherwise add even more complexity)
adds additional test complexity to make sure both compiler generated code and fmt output are the same