Repository navigation
Description
https://github.com/catenacyber/perfsprint exists. I interpret this as an attractive nuisance: most Go programmers probably don't know that we're able to aggressively optimize a+b but not fmt.Sprintf("%v%v", a, b), which leads to a frankly unnecessary "readability vs performance" tradeoff.
There's a few avenues for us to optimize. The most obvious ones are those where a temporary string gets
materialized anyways, because the verb is %v or %s and the type a concrete string or []byte, or would result in a call to String() or Error().
We could further optimize %d and friends, but those will requiring sizing+format helpers in the runtime, since we can't just insert calls to strconv.
This is likely worth it even in cold code for code size reasons, because Sprintf often boxes everything in sight at the callsite. Some cost analysis is potentially necessary to decide when the rewrite is worth it. Most format calls are in cold error-handling code.
So, when is this sound?
- The callee is
fmt.Sprint*. - The format operand is a constant string.
- The format contains only
%%,%s,%v, possibly with arg indices. Precision, width, etc disqualify the rewrite. - The verb count equals the argument count exactly.
- Each argument must have be devirtualizable.
- The underlying type is
stringor[]byte(in which case the verb must be %s), or it providesErrororString, but notFormat.
For condition 6, we must handle the funny panic case whenever we have to call a method to get the actual concat argument. We will likely need to introduce approximately this function:
func runtime.callFmt(p unsafe.Pointer, f func(unsafe.Pointer) string) string {
defer func() {
if err := recover(); err != nil { return %!v(PANIC=...) }
}()
return f(p)
}
We can elide this if the String function is known to not panic (many of them?). We could even require that for the rewrite.
Rough usage
Lexical counts over the standard library and cmd at tip, as an upper bound only:
| shape | count |
|---|---|
fmt.Sprintf calls total |
4015 |
constant format whose only verbs are %s |
799 |
constant format whose only verbs are %d |
1056 |
format containing %v |
640 |
These are just some random greps, which doesn't account for interfaces. I can probably put together a
very basic form of this rewrite for String/Error-free string and []byte to get something a bit more
accurate, particularly since my interest in this is more code size than anything else.
It's worthwhile to note that https://go-review.googlesource.com/c/go/+/20904 did this rewrite by hand in the
compiler for performance, which kind of indicates to me it has serious attractive nuisance potential. My
perspective is that common idioms should be optimized, even if that means intrinsifying random stdlib functions (@dr2chase and I discussed similar special treatment for regexp.Compile some time ago).
I also think it is worthwhile to consider whether there should be special "append" versions of the fmt.S* functions. This is mostly on my mind because this does not address fmt.Fprintf(buf, ...) where buf is something like strings.Builder or bytes.Buffer. I do not have interest in proposing new fmt functions; instead i would like to find some way that Fprintf can specialize itself for certain key stdlib writer functions. Given that internally fmt just splats to a temporary buffer, there may even be a way to do this without clever shims... e.g. if Write() always just appends to a buffer, we can probably just do some kind of rewrite in the compiler.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
gabyhelp commentedon Aug 29, 2026
Related Issues
Related Code Changes
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Jorropo commentedon Aug 29, 2026
I've thought about doing so but the simple cases are also the ones where you need the compiler the least.
I've got a plan to write an advanced partial evaluator to run as much of json's code as possible at compile time. It would give codegen speed for json without writing a second codegen json impl.
This exact same code could handle Sprintf with a const format.
It'll take lots of time so might be done in a couple years.
randall77 commentedon Aug 29, 2026
I want to avoid hard-coding the semantics of stdlib functions in the compiler, to the extent we can. We kind of have to do
math/bitsand similar, but I'd rather leave the semantics offmtout of the compiler.https://go-review.googlesource.com/c/go/+/819500/comments/26f3ec04_3fc738b2
adonovan commentedon Aug 31, 2026
I agree with Keith. If the compiler cheats on
fmt.Sprintf("%s", x), it may make debugging fmt very confusing. (Unless you propose that the compiler should prove the identity before it applies the optimization, to avoid spuriously triggering on modified source code, but that seems infeasible.)A more fruitful line of optimization would be for fmt itself to specialize certain arguments such as ("%s", string) or ("%s%s", string, string) if these are sufficiently numerous (though I am skeptical).
mcy commentedon Aug 31, 2026
Keith: I definitely sympathize with hard-coding semantics like this. However, I think there's a key observation: the semantics of the stdlib are hard-coded into the 1.0 compat guarantee.
We can never change the output of very simple format strings, so it's not like we lose any freedom for evolving the standard library. If the compiler and standard library ever drift, that's a breaking change that has to be rolled back.
That said, I am going to cook up benchmarks anyways, because I would like to see whether this actually moves the needle for very simple cases.
@Jorropo: is there a writeup for this somewhere? I would be interested in the details. I somewhat worry about the degree to which that is sensitive to obstructions due to side effects, of course...
Jorropo commentedon Aug 31, 2026
I havn't wrote up the idea anywhere beyond a couple chats.
If you want to learn about the technology lookup rpython and graalvm for the compiler part.
And tinygo's interp package for the partial evaluation part.
The Tl;Dr would be: to run an rpython / graalvm like compiler but rather than using a tracing jit to generate traces, we would use a partial evaluator.
There are couple minor details that need to be fleshed out like having to solve the halting problem to make a perfect implementation, so it can't be perfect.
Or having an interpreter allowing to execute SSA IR at compile time along with a memory emulator able to allocate heap memory at compile time that then becomes a seed heap region in the binary.
Or lastly, would that even make sense to have in the go compiler ? Would be pretty complex and I'm not sure of the tradeoffs.
mcy commentedon Aug 31, 2026
I think the biggest problem is that Go is violently concurrent even at a very basic level, so it seems very easy for such a thing to be non-deterministic. Not to mention that it's kind of unstable wrt whether you successfully constant-evaluate something or not, relative to nominally non-functional changes in dependencies... for example, if user code suddenly does something that just happens to exhaust the evaluation fuel...
randall77 commentedon Sep 8, 2026
Another option here is to recognize this as some sort of
go fixpattern and update the source code to the simpler form.