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

♻️Refactor: replace treePath with treePathHash in DefaultCtx to reduce memory usage #3368

Merged
merged 1 commit into from
Mar 25, 2025

Conversation

ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Mar 24, 2025

Description

In the default context, the 3-byte-long treePath can be encoded as an int. Therefore, reduce the size of DefaultCtx and treeStack

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 9J14 96-Core Processor                
                                 │   old.txt     │               new.txt                │
                                 │    sec/op     │    sec/op     vs base                │
_Router_NotFound-16                 546.5n ±  1%   467.3n ±  0%  -14.50% (p=0.000 n=20)
_Router_Handler-16                 101.50n ±  0%   96.75n ±  1%   -4.68% (p=0.000 n=20)
_Router_Handler_Strict_Case-16      91.91n ±  0%   86.66n ±  1%   -5.71% (p=0.000 n=20)
_Router_Chain-16                    308.1n ±  1%   305.4n ±  0%   -0.89% (p=0.000 n=20)
_Router_WithCompression-16          310.8n ±  0%   305.4n ±  0%   -1.72% (p=0.000 n=20)
_Router_Next-16                     57.34n ±  1%   54.20n ±  1%   -5.48% (p=0.000 n=20)
_Router_Next_Default-16             46.96n ±  1%   41.56n ±  1%  -11.49% (p=0.000 n=20)
_Router_Next_Default_Parallel-16    7.491n ± 24%   7.886n ± 24%        ~ (p=0.565 n=20)
_Router_Handler_CaseSensitive-16    92.55n ±  1%   86.89n ±  1%   -6.12% (p=0.000 n=20)
_Router_Handler_Unescape-16         114.9n ±  1%   114.5n ±  0%   -0.26% (p=0.008 n=20)
_Router_Handler_StrictRouting-16    92.55n ±  1%   86.98n ±  0%   -6.01% (p=0.000 n=20)
_Router_Github_API-16               149.5µ ±  0%   147.4µ ±  0%   -1.38% (p=0.000 n=20)
geomean                             183.4n         175.1n         -4.55%

                                 │   old.txt    │              new.txt                │
                                 │     B/op     │    B/op     vs base                 │
_Router_NotFound-16                80.00 ± 0%     80.00 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler-16                 0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_Strict_Case-16     0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Chain-16                   48.00 ± 0%     48.00 ± 0%       ~ (p=1.000 n=20) ¹
_Router_WithCompression-16         48.00 ± 0%     48.00 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next-16                    0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next_Default-16            0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next_Default_Parallel-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_CaseSensitive-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_Unescape-16        0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_StrictRouting-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Github_API-16              0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
geomean                                       ²               +0.00%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                 │   old.txt    │              new.txt                │
                                 │  allocs/op   │ allocs/op   vs base                 │
_Router_NotFound-16                3.000 ± 0%     3.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler-16                 0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_Strict_Case-16     0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Chain-16                   3.000 ± 0%     3.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_WithCompression-16         3.000 ± 0%     3.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next-16                    0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next_Default-16            0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Next_Default_Parallel-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_CaseSensitive-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_Unescape-16        0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Handler_StrictRouting-16   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
_Router_Github_API-16              0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=20) ¹
geomean                                       ²               +0.00%                ²
¹ all samples are equal
² summaries must be >0 to compute geomean

Type of change

Please delete options that are not relevant.

  • Performance improvement (non-breaking change which improves efficiency)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Sorry, something went wrong.

Copy link
Contributor

coderabbitai bot commented Mar 24, 2025

Walkthrough

The changes refactor how tree paths are managed across several modules by replacing string-based keys with integer-based keys throughout the routing stack. In the core application and router files, the treeStack field and related logic now use integer keys. Similarly, in the context-related files, the string field/method for tree paths has been replaced by an integer hash (treePathHash) along with corresponding constant and interface changes. Helper functions have been updated to align with these modifications in route matching.

Changes

File(s) Change Summary
app.go Updated treeStack field type from []map[string][]*Route to []map[int][]*Route and revised its initialization in the New function.
ctx.go, ctx_interface.go, ctx_interface_gen.go Replaced string-based tree path references with an integer hash: removed treePath and getTreePath, added treePathHash and getTreePathHash, and defined a new constant maxDetectionPaths.
helpers.go, router.go Modified logic to access tree paths using treePathHash instead of string keys; updated fallback key from "" to 0 and adjusted route tree merging in router.go.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant C as Client
    participant D as DefaultCtx
    participant A as App
    participant TS as TreeStack

    C->>D: Send Request
    D->>D: Compute treePathHash from detectionPath
    D->>A: Invoke route matching (next)
    A->>TS: Retrieve routes using treePathHash
    alt Key exists
        TS-->>A: Return matching routes
    else Fallback
        A->>TS: Retrieve routes using fallback key 0
        TS-->>A: Return fallback routes
    end
    A-->>D: Return matching result
    D-->>C: Final Response

Poem

I’m just a rabbit with a happy beat,
Hopping through code with nimble feet.
Strings turned to ints in our routing land,
Tree paths now hashed by a clever hand.
Code rabbits cheer under the moon’s soft light,
Celebrating changes both merry and bright!
🐇💻


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef40c04 and b72e1c2.

📒 Files selected for processing (6)
  • app.go (2 hunks)
  • ctx.go (4 hunks)
  • ctx_interface.go (1 hunks)
  • ctx_interface_gen.go (1 hunks)
  • helpers.go (2 hunks)
  • router.go (3 hunks)

🪧 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 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

codecov bot commented Mar 24, 2025

Codecov Report

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

Project coverage is 83.71%. Comparing base (ef40c04) to head (b72e1c2).

Files with missing lines Patch % Lines
helpers.go 50.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3368      +/-   ##
==========================================
- Coverage   83.71%   83.71%   -0.01%     
==========================================
  Files         118      118              
  Lines       11722    11721       -1     
==========================================
- Hits         9813     9812       -1     
  Misses       1482     1482              
  Partials      427      427              
Flag Coverage Δ
unittests 83.71% <92.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ksw2000 ksw2000 marked this pull request as ready for review March 24, 2025 15:46
@ksw2000 ksw2000 requested a review from a team as a code owner March 24, 2025 15:46
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 24, 2025 15:46
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 24, 2025
@ReneWerner87 ReneWerner87 merged commit 4bf2929 into gofiber:main Mar 25, 2025
33 of 37 checks passed
@ksw2000 ksw2000 changed the title ♻️Refactor: reduce DefaultCtx from 736 to 728 bytes ♻️Refactor: replace treePath by treePathHash in DefaultCtx to save 8 bytes Mar 25, 2025
@ksw2000 ksw2000 changed the title ♻️Refactor: replace treePath by treePathHash in DefaultCtx to save 8 bytes ♻️Refactor: replace treePath by treePathHash in DefaultCtx to reduce memory usage Mar 25, 2025
@ksw2000 ksw2000 changed the title ♻️Refactor: replace treePath by treePathHash in DefaultCtx to reduce memory usage ♻️Refactor: replace treePath with treePathHash in DefaultCtx to reduce memory usage Mar 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

None yet

2 participants