Proposal
In fmt.doPrint, the check to determine if an argument is a string currently
always uses reflect.TypeOf(arg).Kind() == reflect.String, even for plain
string values. This adds unnecessary reflection overhead in the common case.
The proposal is to try a direct type assertion arg.(string) first. If it
succeeds, isString is true and no reflection is needed. If it fails and
arg is non-nil, fall back to reflect to support named string types (e.g.,
type MyString string).
Motivation
Sprint, Fprint, Print and their variants are frequently used with plain
strings. Avoiding a reflect call for each argument in these common paths
provides a measurable performance improvement without any change in behavior.
Compatibility
The behavior is unchanged:
nil arguments are not treated as strings (type assertion on nil interface
is safe).
- Named string types are still recognized as strings via the reflection
fallback.
- Spacing between non-string arguments remains identical.
No API changes, no user-visible effects.
Implementation
A trivial change to src/fmt/print.go in doPrint. The type assertion is
the common fast path; the reflection path is only entered for non-nil,
non-plain-string arguments.
Related CL will be uploaded for review.
Proposal
In
fmt.doPrint, the check to determine if an argument is a string currentlyalways uses
reflect.TypeOf(arg).Kind() == reflect.String, even for plainstringvalues. This adds unnecessary reflection overhead in the common case.The proposal is to try a direct type assertion
arg.(string)first. If itsucceeds,
isStringis true and no reflection is needed. If it fails andargis non-nil, fall back toreflectto support named string types (e.g.,type MyString string).Motivation
Sprint,Fprint,Printand their variants are frequently used with plainstrings. Avoiding a reflect call for each argument in these common paths
provides a measurable performance improvement without any change in behavior.
Compatibility
The behavior is unchanged:
nilarguments are not treated as strings (type assertion on nil interfaceis safe).
fallback.
No API changes, no user-visible effects.
Implementation
A trivial change to
src/fmt/print.goindoPrint. The type assertion isthe common fast path; the reflection path is only entered for non-nil,
non-plain-string arguments.
Related CL will be uploaded for review.