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

perf: do less allocs in hasher #287

Merged
merged 3 commits into from
Jan 20, 2025
Merged

perf: do less allocs in hasher #287

merged 3 commits into from
Jan 20, 2025

Conversation

cristaloleg
Copy link
Contributor

@cristaloleg cristaloleg commented Jan 17, 2025

Have found few places after #285 that can be improved a bit more without going into enigma mode™:

$ go-perftuner bstat a.txt c.txt
args: [a.txt c.txt]name                       old time/op    new time/op    delta
ComputeRoot/64-leaves-10     37.5µs ± 1%    34.2µs ± 2%   -8.76%  (p=0.000 n=8+10)
ComputeRoot/128-leaves-10    73.9µs ± 0%    68.6µs ± 2%   -7.21%  (p=0.000 n=9+10)
ComputeRoot/256-leaves-10     151µs ± 2%     140µs ± 4%   -6.91%  (p=0.000 n=9+10)
ComputeRoot/20k-leaves-10    14.9ms ± 2%    13.2ms ± 4%  -11.53%  (p=0.000 n=10+10)

name                       old alloc/op   new alloc/op   delta
ComputeRoot/64-leaves-10     57.6kB ± 0%    31.7kB ± 0%  -45.02%  (p=0.000 n=10+10)
ComputeRoot/128-leaves-10     109kB ± 0%      57kB ± 0%  -47.83%  (p=0.000 n=10+10)
ComputeRoot/256-leaves-10     224kB ± 0%     120kB ± 0%  -46.45%  (p=0.000 n=10+10)
ComputeRoot/20k-leaves-10    26.2MB ± 0%    12.3MB ± 0%  -53.11%  (p=0.000 n=9+10)

name                       old allocs/op  new allocs/op  delta
ComputeRoot/64-leaves-10        590 ± 0%       527 ± 0%  -10.68%  (p=0.000 n=10+10)
ComputeRoot/128-leaves-10     1.17k ± 0%     1.04k ± 0%  -10.86%  (p=0.000 n=10+10)
ComputeRoot/256-leaves-10     2.33k ± 0%     2.07k ± 0%  -10.95%  (p=0.000 n=10+10)
ComputeRoot/20k-leaves-10      181k ± 0%      161k ± 0%  -11.08%  (p=0.000 n=10+10)

Summary by CodeRabbit

  • Refactor
    • Optimized hashing methods for improved efficiency.
    • Simplified data preparation for leaf and node hashing.
    • Reduced unnecessary memory allocations in hash calculations.
  • Tests
    • Enhanced the TestEmptyRoot function with sub-tests for better validation.
    • Improved variable naming for clarity in test cases.
    • Updated assertions for better readability in test results.

@cristaloleg cristaloleg added the enhancement New feature or request label Jan 17, 2025
@cristaloleg cristaloleg self-assigned this Jan 17, 2025
Copy link

coderabbitai bot commented Jan 17, 2025

Walkthrough

The pull request focuses on optimizing the NmtHasher struct in the hasher.go file. The changes primarily involve refactoring the EmptyRoot, HashLeaf, and HashNode methods to improve data preparation and hashing efficiency. The modifications streamline the process of creating and processing data for hashing by eliminating unnecessary slice allocations and simplifying the method implementations. Additionally, the hasher_test.go file has been updated to enhance the structure and clarity of the tests related to the EmptyRoot method.

Changes

File Change Summary
hasher.go - Refactored EmptyRoot() to create a zeroed slice based on namespace length and base hasher size
- Simplified HashLeaf() by directly writing LeafPrefix and ndata to the hasher
- Optimized HashNode() by directly writing NodePrefix, left, and right to the hasher
hasher_test.go - Updated TestEmptyRoot to include two sub-tests for validating EmptyRoot behavior
- Improved variable names for clarity
- Changed assertions to assert.Equal for better readability

Possibly related PRs

Poem

🐰 Hashing with grace, a rabbit's delight,
Slices trimmed down, code shining bright.
No more allocations, just pure and clean,
Our hasher now dances with algorithmic sheen!
Efficiency leaps in a single bound 🚀


📜 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 192f6d2 and 7301b8c.

📒 Files selected for processing (1)
  • hasher_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • hasher_test.go

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

res = append(res, minNs...)
res = append(res, maxNs...)

// Note this seems a little faster than calling several Write()s on the
// underlying Hash function (see:
// https://github.com/google/trillian/pull/1503):
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This comment is outdated. For the last ~5 years compiler became better and doing a few .Write() is cheaper then allocating a big slice and copying into it.

@@ -306,19 +305,13 @@ func (n *NmtHasher) HashNode(left, right []byte) ([]byte, error) {
// compute the namespace range of the parent node
minNs, maxNs := computeNsRange(lRange.Min, lRange.Max, rRange.Min, rRange.Max, n.ignoreMaxNs, n.precomputedMaxNs)

res := make([]byte, 0, len(minNs)*2)
res := make([]byte, 0, len(minNs)+len(maxNs)+h.Size())
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We're appending hash to the res so adding place for hash.


return digest
digest := make([]byte, zeroSize, fullSize)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Literally what comment above says: we need zeroed 2 n.NamespaceLen + space for hash.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
hasher.go (1)

308-314: Good optimization with room for minor improvement

The changes effectively reduce allocations through pre-allocation and direct writes. However, we could further optimize the slice allocation.

Consider this minor optimization to reduce the number of append operations:

-res := make([]byte, 0, len(minNs)+len(maxNs)+h.Size())
-res = append(res, minNs...)
-res = append(res, maxNs...)
+totalSize := len(minNs)+len(maxNs)+h.Size()
+res := make([]byte, len(minNs)+len(maxNs), totalSize)
+copy(res, minNs)
+copy(res[len(minNs):], maxNs)

This approach:

  1. Pre-allocates the slice with the correct size for minNs and maxNs
  2. Uses copy instead of append, which can be more efficient
  3. Maintains the same capacity for the final hash
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b1b3d8 and a0103f9.

📒 Files selected for processing (1)
  • hasher.go (3 hunks)
🔇 Additional comments (2)
hasher.go (2)

157-162: Excellent optimization of slice allocation!

The changes effectively reduce memory allocations by:

  1. Pre-allocating the slice with exact capacity
  2. Utilizing Go's zero-value initialization
  3. Eliminating unnecessary append operations

This aligns well with the PR's performance objectives.


195-196: Efficient optimization of hash computation!

Direct writes to the hasher eliminate unnecessary slice allocations while maintaining the same hashing semantics. This is a clean optimization that contributes to the observed performance improvements.

@rootulp rootulp mentioned this pull request Jan 17, 2025
rootulp
rootulp previously approved these changes Jan 17, 2025
Copy link
Collaborator

@rootulp rootulp left a comment

Choose a reason for hiding this comment

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

LGTM with two optional changes (or FLUPs):

  1. Refactored EmptyRoot unit test to confirm that the empty root remains exactly the same before and after this PR test: empty root #288
  2. Remove all the nolint:errcheck

Thanks for including the perf analysis in the PR description 👍 great work


return digest
digest := make([]byte, zeroSize, fullSize)
return n.baseHasher.Sum(digest)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I wrote a unit test to verify this refactor doesn't modify the returned empty root: #288

Didn't want to push to your branch without permission but feel free to include in this PR if it helps

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. Have included your test, thank you!

hasher.go Outdated
Comment on lines 195 to 196
h.Write([]byte{LeafPrefix}) //nolint:errcheck
h.Write(ndata) //nolint:errcheck
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: there's a lint disable on line 180. Can we remove all the lint disables and actually check for errors?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. TBH there is no sense to check 'cause hasher never returns any errors. It's even stated in crypto.Hash doc:

type Hash interface {
	// Write (via the embedded io.Writer interface) adds more data to the running hash.
	// It never returns an error.
	io.Writer

So we can drop this for sure (including line 180).

evan-forbes
evan-forbes previously approved these changes Jan 17, 2025
@cristaloleg cristaloleg dismissed stale reviews from evan-forbes and rootulp via 192f6d2 January 18, 2025 08:37
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
hasher_test.go (1)

904-905: Fix variable naming inconsistencies.

There are two naming issues:

  1. nIDSzie has a typo (should be nIDSize)
  2. ignoreMaxNS is inconsistent with the codebase style (should be ignoreMaxNs)

Apply this diff to fix the naming:

-		nIDSzie := 1
-		ignoreMaxNS := true
+		nIDSize := 1
+		ignoreMaxNs := true
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0103f9 and 192f6d2.

📒 Files selected for processing (2)
  • hasher.go (3 hunks)
  • hasher_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • hasher.go
🔇 Additional comments (1)
hasher_test.go (1)

903-927: Well-structured test implementation!

The test function is well-designed with:

  • Clear sub-tests for verifying both correctness and consistency
  • Good edge case coverage testing hasher state independence
  • Clear comments explaining the test purposes

@evan-forbes evan-forbes merged commit a336f12 into main Jan 20, 2025
8 checks passed
@evan-forbes evan-forbes deleted the hasher/less-allocs branch January 20, 2025 13:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants