Skip to content

Speed up StringWrapper: cheaper pre-check, parse reuse, lighter AST verification #250

Open

Description

@abashev

Upstream: google/google-java-format#1533
Kind: idea | Priority: low

google-java-format#1533 (open, a Google-internal change exported by copybara, opened 2026-11-20) reduces the cost of string-literal wrapping without changing output. It replaces the line iterator in the "does anything need wrapping" check with an allocation-free scan that also requires a quote character on a long line inside the requested ranges; it reuses the parsed compilation unit between the first pass and the reflow and avoids reflowing the same concatenation chain twice. Its biggest saving is the safety check: instead of parsing the whole file twice with string folding and comparing the trees, it parses a tiny synthetic class holding only the replaced expressions and compares literal values, falling back to the full-file comparison when the parent expression could change operator precedence (casts, arithmetic, unary operators). The author reports roughly 1.5x to 2x faster formatting on files with long strings.

Why it matters to us: our StringWrapper has the same shape (a needWrapping check on a line iterator, a first pass, and a verification step that parses the input and the result in full and compares their string forms). On large files with a few long strings the double full parse is the dominant cost. This is performance only, so priority is low, but the verification shortcut is the part worth studying because it must not weaken the safety guarantee. Note that the PR also touches the upstream cleanups pipeline, which we do not have in this form (see our existing ticket on the unified cleanups pipeline and our #157), so only the StringWrapper part is portable on its own.

Affected files in our repo:

  • open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java (needWrapping, wrapOnce, the verification parse, Reflower)
  • open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java and FormatFileCallable.java (callers of StringWrapper.wrap and linesNeedWrapping)
  • open-java-format-benchmarks (to measure before and after)

Suggested action: watch until the PR is merged or revised, then adopt-the-idea for the StringWrapper part only: benchmark our current cost first, and port the precedence-aware fallback together with its two new tests, since that is the risky piece. No formatting output changes, so no Before/After examples.


Filed from an upstream-watch ticket after manual review.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions