Skip to content

Conversation

@vdarulis
Copy link
Contributor

@vdarulis vdarulis commented Jun 4, 2025

EncodeBetter and EncodeBest were checking len of the destination buffer, unlike the Snappy flavors or plain s2.Encode(), which can lead to a surprising amount of allocations, if the caller is careful to reuse buffers.

I fixed the benchmarks to actively try and reuse memory, and ran the comparison with updated tests on master vs this branch to demonstrate the alloc difference:

goos: darwin
goarch: arm64
pkg: github.com/klauspost/compress/s2
cpu: Apple M1 Pro

                                   │       old        │                   new                    │
                                   │       B/op       │     B/op      vs base                    │
TwainEncode1e6/default-10                0.000 ± 0%       0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/better-10              1496.0Ki ± 0%     512.0Ki ± 0%   -65.78% (p=0.002 n=6)
TwainEncode1e6/best-10                 5.461Mi ± 0%     4.500Mi ± 0%   -17.60% (p=0.002 n=6)
TwainEncode1e6/snappy-default-10         0.000 ± 0%       0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/snappy-better-10        256.0Ki ± 0%     256.0Ki ± 0%         ~ (p=0.727 n=6)
TwainEncode1e6/snappy-best-10          4.500Mi ± 0%     4.500Mi ± 0%         ~ (p=0.868 n=6)
TwainEncode1e6/snappy-ref-noasm-10     1.117Mi ± 0%     0.000Mi ± 0%  -100.00% (p=0.002 n=6)
TwainEncode1e7/default-10                0.000 ± 0%       0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/better-10             10280.0Ki ± 0%     512.0Ki ± 0%   -95.02% (p=0.002 n=6)
TwainEncode1e7/best-10                14.039Mi ± 0%     4.500Mi ± 0%   -67.95% (p=0.002 n=6)
TwainEncode1e7/snappy-default-10         0.000 ± 0%       0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/snappy-better-10        256.0Ki ± 0%     256.0Ki ± 0%         ~ (p=0.455 n=6)
TwainEncode1e7/snappy-best-10          4.500Mi ± 0%     4.500Mi ± 0%         ~ (p=1.000 n=6)
TwainEncode1e7/snappy-ref-noasm-10     11.13Mi ± 0%      0.00Mi ± 0%  -100.00% (p=0.002 n=6)
geomean                                             ²                 ?                      ² ³
¹ all samples are equal
² summaries must be >0 to compute geomean
³ ratios must be >0 to compute geomean

                                   │      old      │                  new                   │
                                   │   allocs/op   │ allocs/op   vs base                    │
TwainEncode1e6/default-10            0.000 ±  0%     0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/better-10             3.000 ±  0%     1.000 ± 0%   -66.67% (p=0.002 n=6)
TwainEncode1e6/best-10               5.000 ± 20%     3.000 ± 0%   -40.00% (p=0.002 n=6)
TwainEncode1e6/snappy-default-10     0.000 ±  0%     0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/snappy-better-10      1.000 ±  0%     1.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/snappy-best-10        3.000 ±  0%     3.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e6/snappy-ref-noasm-10   1.000 ±  0%     0.000 ± 0%  -100.00% (p=0.002 n=6)
TwainEncode1e7/default-10            0.000 ±  0%     0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/better-10             3.000 ±  0%     1.000 ± 0%   -66.67% (p=0.002 n=6)
TwainEncode1e7/best-10               4.000 ± 25%     2.000 ± 0%   -50.00% (p=0.002 n=6)
TwainEncode1e7/snappy-default-10     0.000 ±  0%     0.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/snappy-better-10      1.000 ±  0%     1.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/snappy-best-10        2.000 ±  0%     2.000 ± 0%         ~ (p=1.000 n=6) ¹
TwainEncode1e7/snappy-ref-noasm-10   2.000 ±  0%     0.000 ± 0%  -100.00% (p=0.002 n=6)
geomean                                          ²               ?                      ² ³
¹ all samples are equal

Note that since I'm running this on ARM, lTable/sTable escape to heap in the non-asm path - hence it's not zero-alloc, but the S2 mode now is identical to Snappy in terms of allocs.

Summary by CodeRabbit

  • Performance Improvements

    • Enhanced buffer management in encoding and decoding processes for more efficient memory usage.
    • Improved benchmark accuracy by reusing buffers and refining metric reporting in performance tests.
  • Tests

    • Updated benchmark tests to provide more reliable and consistent measurement of encoding and decoding performance.

@coderabbitai
Copy link

coderabbitai bot commented Jun 4, 2025

📝 Walkthrough

Walkthrough

The changes update buffer allocation and reuse logic in encoding and decoding functions. Instead of checking the buffer's length, the code now checks its capacity before allocating or reslicing. Benchmark tests are also updated to reuse buffers efficiently, improve error handling, and ensure accurate metric reporting during performance measurements.

Changes

File(s) Change Summary
internal/snapref/encode.go Modified buffer allocation in Encode to check capacity instead of length before allocating or reslicing.
s2/encode.go Updated EncodeBetter and EncodeBest functions to use capacity checks for buffer allocation and reslicing.
s2/s2_test.go Refactored benchmarks to reuse buffers, improve error handling, and report metrics based on actual buffer use.

Sequence Diagram(s)

sequenceDiagram
    participant Benchmark as Benchmark Function
    participant Buffer as Reusable Buffer
    participant Encode as Encode/Decode Function

    Benchmark->>Buffer: Allocate buffer with sufficient capacity
    loop Each iteration
        Benchmark->>Buffer: Reslice buffer as needed
        Benchmark->>Encode: Call Encode/Decode with Buffer
        Encode-->>Benchmark: Return encoded/decoded data
        Benchmark->>Benchmark: Check for errors and record metrics
    end
Loading
sequenceDiagram
    participant Caller as Caller Function
    participant Buffer as Destination Buffer
    participant Encode as Encode Function

    Caller->>Buffer: Check buffer capacity
    alt Capacity < required
        Caller->>Buffer: Allocate new buffer with required length
    else Capacity sufficient
        Caller->>Buffer: Reslice buffer to required length
    end
    Caller->>Encode: Perform encoding using Buffer
    Encode-->>Caller: Return encoded data in Buffer
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33f59b4 and ea02415.

📒 Files selected for processing (3)
  • internal/snapref/encode.go (1 hunks)
  • s2/encode.go (2 hunks)
  • s2/s2_test.go (5 hunks)
🔇 Additional comments (5)
internal/snapref/encode.go (1)

23-27: Excellent buffer management improvement!

The change from checking len(dst) to cap(dst) enables proper buffer reuse by leveraging existing capacity. The addition of dst = dst[:n] correctly sets the buffer length when capacity is sufficient, avoiding unnecessary allocations.

s2/encode.go (2)

120-124: Perfect consistency with buffer management pattern!

EncodeBetter now properly checks buffer capacity instead of length, matching the behavior of the base Encode function and enabling efficient buffer reuse.


164-168: Excellent alignment with the buffer reuse strategy!

EncodeBest now uses the same capacity-based buffer management as the other encoding functions, completing the consistency improvements across all s2 encoding variants.

s2/s2_test.go (2)

391-442: Excellent benchmark improvements for buffer reuse testing!

The benchDecode updates properly implement buffer reuse by:

  • Allocating reusable buffers once with appropriate capacity
  • Moving error handling outside the benchmark loop for accuracy
  • Consistently applying the pattern across all decode benchmark subtests

These changes ensure accurate measurement of the new buffer management behavior.


454-521: Outstanding benchmark optimization for encoding tests!

The benchEncode improvements effectively test buffer reuse by:

  • Allocating destination buffers once per subtest with proper capacity
  • Capturing returned slices to update buffers between iterations
  • Moving b.ResetTimer() calls to exclude allocation overhead
  • Using actual buffer lengths for metric reporting instead of redundant encoding calls

This ensures the benchmarks accurately reflect the memory allocation improvements achieved by the capacity-based buffer management.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Owner

@klauspost klauspost left a comment

Choose a reason for hiding this comment

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

Hmmm.. Yeah, that seems inconsistent.

It is not a 0-risk change, but close enough that we can take that risk.

@vdarulis vdarulis changed the title Check for cap, not len of buffer in s2.EncodeBetter/Best s2: check for cap, not len of buffer in EncodeBetter/Best Jun 4, 2025
@klauspost klauspost merged commit 3fb7836 into klauspost:master Jun 5, 2025
22 checks passed
@vdarulis vdarulis deleted the v/s2_len_cap branch June 6, 2025 17:00
@vdarulis
Copy link
Contributor Author

vdarulis commented Jun 6, 2025

@klauspost thank you for the fast review and merge!

hantang pushed a commit to qundao/mirror-forgejo that referenced this pull request Oct 21, 2025
This PR contains the following updates:

| Package | Change | Age | Confidence |
|---|---|---|---|
| [github.com/klauspost/compress](https://github.com/klauspost/compress) | `v1.18.0` -> `v1.18.1` | [![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fklauspost%2fcompress/v1.18.1?slim=true)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fklauspost%2fcompress/v1.18.0/v1.18.1?slim=true)](https://docs.renovatebot.com/merge-confidence/) |

---

### Release Notes

<details>
<summary>klauspost/compress (github.com/klauspost/compress)</summary>

### [`v1.18.1`](https://github.com/klauspost/compress/releases/tag/v1.18.1)

[Compare Source](klauspost/compress@v1.18.0...v1.18.1)

#### What's Changed

- zstd: Fix incorrect buffer size in dictionary encodes by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1059](klauspost/compress#1059)
- s2: check for cap, not len of buffer in EncodeBetter/Best by [@&#8203;vdarulis](https://github.com/vdarulis) in [#&#8203;1080](klauspost/compress#1080)
- zstd: Add simple zstd EncodeTo/DecodeTo functions by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1079](klauspost/compress#1079)
- zlib: Avoiding extra allocation in zlib.reader.Reset by [@&#8203;travelpolicy](https://github.com/travelpolicy) in [#&#8203;1086](klauspost/compress#1086)
- gzhttp: remove redundant err check in zstdReader by [@&#8203;ryanfowler](https://github.com/ryanfowler) in [#&#8203;1090](klauspost/compress#1090)
- Run modernize. Deprecate Go 1.22 by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1095](klauspost/compress#1095)
- flate: Simplify matchlen by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1101](klauspost/compress#1101)
- flate: Add examples by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1102](klauspost/compress#1102)
- flate: Use exact sizes for huffman tables by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1103](klauspost/compress#1103)
- flate: Faster load+store by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1104](klauspost/compress#1104)
- Add notice to S2 about MinLZ by [@&#8203;klauspost](https://github.com/klauspost) in [#&#8203;1065](klauspost/compress#1065)

#### New Contributors

- [@&#8203;wooffie](https://github.com/wooffie) made their first contribution in [#&#8203;1069](klauspost/compress#1069)
- [@&#8203;vdarulis](https://github.com/vdarulis) made their first contribution in [#&#8203;1080](klauspost/compress#1080)
- [@&#8203;travelpolicy](https://github.com/travelpolicy) made their first contribution in [#&#8203;1086](klauspost/compress#1086)
- [@&#8203;ryanfowler](https://github.com/ryanfowler) made their first contribution in [#&#8203;1090](klauspost/compress#1090)

**Full Changelog**: <klauspost/compress@v1.18.0...v1.18.1>

</details>

---

### Configuration

📅 **Schedule**: Branch creation - Between 12:00 AM and 03:59 AM ( * 0-3 * * * ) (UTC), Automerge - Between 12:00 AM and 03:59 AM ( * 0-3 * * * ) (UTC).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MS4xNTIuOSIsInVwZGF0ZWRJblZlciI6IjQxLjE1Mi45IiwidGFyZ2V0QnJhbmNoIjoiZm9yZ2VqbyIsImxhYmVscyI6WyJkZXBlbmRlbmN5LXVwZ3JhZGUiLCJ0ZXN0L25vdC1uZWVkZWQiXX0=-->

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/9786
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Renovate Bot <forgejo-renovate-action@forgejo.org>
Co-committed-by: Renovate Bot <forgejo-renovate-action@forgejo.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants