Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

go/vt/sqlparser: improve performance in TrackedBuffer formatting #16364

Merged
merged 2 commits into from
Sep 16, 2024

Conversation

mattrobenolt
Copy link
Contributor

@mattrobenolt mattrobenolt commented Jul 10, 2024

Two minor things:

  • decently improve formatting integers (%d)
  • WriteArg calls buf.Grow to avoid potentially 2 allocations

For integer formatting, buf.WriteString(fmt.Sprintf(...)) was about the worst way to do it. fmt.Sprintf itself allocates a new string, plus it's %d formatting is much more robust in handling padding and whatnot.

First alternative for free win was using fmt.Fprintf(&buf, ...) instead, which simply avoids the extra allocation and just writes directly to the buffer.

But strconv.Format{I,Ui}nt is quite fast, especially since it has a fast path for "small integers".

Here's a trivial benchmark of all 3 options:

$ benchstat fmt.txt
goos: darwin
goarch: arm64
pkg: x
                       │   fmt.txt   │
                       │   sec/op    │
FormatInt/Sprintf-10     55.51n ± 1%
FormatInt/Fprintf-10     50.76n ± 1%
FormatInt/FormatInt-10   17.16n ± 2%
geomean                  36.43n

                       │  fmt.txt   │
                       │    B/op    │
FormatInt/Sprintf-10     16.00 ± 0%
FormatInt/Fprintf-10     8.000 ± 0%
FormatInt/FormatInt-10   8.000 ± 0%
geomean                  10.08

                       │  fmt.txt   │
                       │ allocs/op  │
FormatInt/Sprintf-10     2.000 ± 0%
FormatInt/Fprintf-10     1.000 ± 0%
FormatInt/FormatInt-10   1.000 ± 0%
geomean                  1.260

So each %d within a format string is considerably faster. This obviously scales linearly with the number of %d's there are.

Related Issue(s)

Part of #16789

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Copy link
Contributor

vitess-bot bot commented Jul 10, 2024

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@vitess-bot vitess-bot bot added NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says labels Jul 10, 2024
@github-actions github-actions bot added this to the v21.0.0 milestone Jul 10, 2024
@@ -288,14 +314,26 @@ func areBothISExpr(op Expr, val Expr) bool {
// WriteArg writes a value argument into the buffer along with
// tracking information for future substitutions.
func (buf *TrackedBuffer) WriteArg(prefix, arg string) {
length := len(prefix) + len(arg)
buf.bindLocations = append(buf.bindLocations, BindLocation{
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a potential follow up:

I got here because WriteArg stood out a bit in a pprof I was looking at for heap allocations, and the other thing that can be done in here with some more work is the bindLocations slice that keeps getting appended to 1 at a time.

So we might want to do a thing where we count up the args first so can we grow the slice, then append to the slice. So adding a method like, GrowArgs(size)

Copy link

codecov bot commented Jul 10, 2024

Codecov Report

Attention: Patch coverage is 93.75000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 68.92%. Comparing base (6fc808d) to head (57b4035).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
go/vt/sqlparser/tracked_buffer.go 93.75% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16364   +/-   ##
=======================================
  Coverage   68.91%   68.92%           
=======================================
  Files        1566     1566           
  Lines      201855   201885   +30     
=======================================
+ Hits       139113   139147   +34     
+ Misses      62742    62738    -4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Two minor things:
* decently improve formatting integers (%d)
* WriteArg calls buf.Grow to avoid potentially 2 allocations

For integer formatting, buf.WriteString(fmt.Sprintf(...)) was about the
worst way to do it. fmt.Sprintf itself allocates a new string, plus it's
%d formatting is much more robust in handling padding and whatnot.

First alternative for free win was using `fmt.Fprintf(&buf, ...)`
instead, which simply avoids the extra allocation and just writes
directly to the buffer.

But strconv.Format{I,Ui}nt is quite fast, especially since it has a fast
path for "small integers".

Here's a trivial benchmark of all 3 options:

```
$ benchstat fmt.txt
goos: darwin
goarch: arm64
pkg: x
                       │   fmt.txt   │
                       │   sec/op    │
FormatInt/Sprintf-10     55.51n ± 1%
FormatInt/Fprintf-10     50.76n ± 1%
FormatInt/FormatInt-10   17.16n ± 2%
geomean                  36.43n

                       │  fmt.txt   │
                       │    B/op    │
FormatInt/Sprintf-10     16.00 ± 0%
FormatInt/Fprintf-10     8.000 ± 0%
FormatInt/FormatInt-10   8.000 ± 0%
geomean                  10.08

                       │  fmt.txt   │
                       │ allocs/op  │
FormatInt/Sprintf-10     2.000 ± 0%
FormatInt/Fprintf-10     1.000 ± 0%
FormatInt/FormatInt-10   1.000 ± 0%
geomean                  1.260
```

So each %d within a format string is considerably faster. This obviously
scales linearly with the number of %d's there are.

Signed-off-by: Matt Robenolt <[email protected]>
@deepthi deepthi added Type: Performance Type: Enhancement Logical improvement (somewhere between a bug and feature) and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Jul 10, 2024
@deepthi
Copy link
Member

deepthi commented Jul 10, 2024

@mattrobenolt would you mind creating an umbrella issue like "VTGate performance improvements" or something similar and referring to that in this series of PRs?

Copy link
Contributor

This PR is being marked as stale because it has been open for 30 days with no activity. To rectify, you may do any of the following:

  • Push additional commits to the associated branch.
  • Remove the stale label.
  • Add a comment indicating why it is not stale.

If no action is taken within 7 days, this PR will be closed.

@github-actions github-actions bot added Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. and removed Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. labels Aug 11, 2024
Copy link
Contributor

This PR is being marked as stale because it has been open for 30 days with no activity. To rectify, you may do any of the following:

  • Push additional commits to the associated branch.
  • Remove the stale label.
  • Add a comment indicating why it is not stale.

If no action is taken within 7 days, this PR will be closed.

@github-actions github-actions bot added Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. and removed Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. labels Sep 11, 2024
@systay systay added Component: Query Serving and removed NeedsIssue A linked issue is missing for this Pull Request labels Sep 16, 2024

// WriteUint writes an unsigned integer into the buffer.
func (buf *TrackedBuffer) WriteUint(v uint64) {
buf.WriteString(strconv.FormatUint(v, 10))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this is still allocating memory when the small-number optimization doesn't trigger, so that isn't great. I think it may be time to leave behind the *strings.Builder used here and instead implementing building ourselves, which would allow us to simplify many things, including using strconv.AppendInt instead of the Format versions. Maybe for another PR!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I assume you're thinking something more specialized like what zap does? https://github.com/uber-go/zap/blob/master/buffer/buffer.go

@systay systay merged commit b5eb928 into vitessio:main Sep 16, 2024
97 checks passed
@mattrobenolt mattrobenolt deleted the tracker-buffer-perf branch September 16, 2024 18:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: Query Serving Type: Enhancement Logical improvement (somewhere between a bug and feature) Type: Performance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants