Skip to content

fmt: use type assertion to avoid reflection in doPrint #80017

Description

@solos

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performance

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions