Skip to content

Conversation

@ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Jul 2, 2025

Description

Reduce iterator time complexity from O(n2) to O(n log n)

  • Request.Params()
  • Request.AllFormData()
goos: darwin
goarch: arm64
pkg: github.com/gofiber/fiber/v3/client
cpu: Apple M4
                        │   old.txt    │           new.txt           │
                        │    sec/op    │   sec/op     vs base        │
_Request_Params-10        135.70n ± 0%   41.01n ± 0%  -69.78% (n=50)
_Request_AllFormData-10   135.60n ± 0%   94.67n ± 0%  -30.18% (n=50)
geomean                    135.6n        62.31n       -54.07%

                        │   old.txt   │          new.txt           │
                        │    B/op     │    B/op     vs base        │
_Request_Params-10        232.00 ± 0%   88.00 ± 0%  -62.07% (n=50)
_Request_AllFormData-10    232.0 ± 0%   184.0 ± 0%  -20.69% (n=50)
geomean                    232.0        127.2       -45.15%

                        │  old.txt   │          new.txt           │
                        │ allocs/op  │ allocs/op   vs base        │
_Request_Params-10        9.000 ± 0%   4.000 ± 0%  -55.56% (n=50)
_Request_AllFormData-10   9.000 ± 0%   6.000 ± 0%  -33.33% (n=50)
geomean                   9.000        4.899       -45.57%

Refactor: call existing functions directly

  • Request.Cookies()
  • Request.PathParams()
  • Cookie.All()
  • Cookie.Reset()
  • PathParam.All()
  • PathParam.Reset()

Type of change

  • 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.

```
goos: darwin
goarch: arm64
pkg: github.com/gofiber/fiber/v3/client
cpu: Apple M4
                        │   old.txt    │           new.txt           │
                        │    sec/op    │   sec/op     vs base        │
_Request_Headers-10       140.15n ± 0%   99.39n ± 1%  -29.08% (n=50)
_Request_Params-10        135.70n ± 0%   41.01n ± 0%  -69.78% (n=50)
_Request_AllFormData-10   135.60n ± 0%   94.67n ± 0%  -30.18% (n=50)
_Headers-10                291.3n ± 0%   156.8n ± 1%  -46.17% (n=50)
geomean                    165.6n        88.20n       -46.73%

                        │   old.txt   │              new.txt               │
                        │    B/op     │    B/op     vs base                │
_Request_Headers-10        200.0 ± 0%   184.0 ± 0%   -8.00% (n=50)
_Request_Params-10        232.00 ± 0%   88.00 ± 0%  -62.07% (n=50)
_Request_AllFormData-10    232.0 ± 0%   184.0 ± 0%  -20.69% (n=50)
_Headers-10                296.0 ± 0%   376.0 ± 0%  +27.03% (p=0.000 n=50)
geomean                    237.6        182.9       -23.00%

                        │  old.txt   │          new.txt           │
                        │ allocs/op  │ allocs/op   vs base        │
_Request_Headers-10       7.000 ± 0%   6.000 ± 0%  -14.29% (n=50)
_Request_Params-10        9.000 ± 0%   4.000 ± 0%  -55.56% (n=50)
_Request_AllFormData-10   9.000 ± 0%   6.000 ± 0%  -33.33% (n=50)
_Headers-10               9.000 ± 0%   6.000 ± 0%  -33.33% (n=50)
geomean                   8.452        5.422       -35.85%
```
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 2, 2025

Walkthrough

The changes standardize map iteration in request parameter handling by introducing a pair struct for sorting keys and values. Methods for accessing parameters, form data, cookies, and path parameters now yield sorted key-value pairs or delegate to generic map utilities, ensuring deterministic order and simplified logic.

Changes

File(s) Change Summary
client/request.go Added pair struct with sort.Interface methods; refactored parameter, form data, cookie, and path param methods to use sorting and unified iteration; updated reset and all methods to use generic utilities.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Request
    participant PairSorter
    participant MapsUtil

    Client->>Request: Call Params()/AllFormData()
    Request->>PairSorter: Collect and sort key-value pairs
    PairSorter-->>Request: Sorted pairs
    Request->>Client: Yield sorted key-value pairs

    Client->>Request: Call Cookies()/PathParams()
    Request->>MapsUtil: Retrieve all entries
    MapsUtil-->>Request: All key-value pairs
    Request->>Client: Return all pairs
Loading

Suggested labels

v3, ⚡️ Performance

Suggested reviewers

  • gaby
  • sixcolors

Poem

Oh, keys and values, once a scattered crowd,
Now sorted neat, their order proud.
With pairs in line and maps made clear,
The code runs swift—no bugs to fear!
🐇✨

Hop, hop, hooray for order’s delight,
Deterministic joy, all day and night!


📜 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 e041d63 and f928d75.

📒 Files selected for processing (1)
  • client/request.go (8 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#0
File: :0-0
Timestamp: 2024-12-01T10:28:36.011Z
Learning: Feature request #3224 has been created to add support for square bracket notation and comma-separated values in multipart form data in Fiber, while maintaining binary data transfer capabilities. This would bring parity with the existing form-urlencoded functionality.
client/request.go (4)
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
🔇 Additional comments (10)
client/request.go (10)

13-13: LGTM: Import addition for sorting functionality.

The sort import is correctly added to support the new sorting-based approach for parameter iteration.


132-148: LGTM: Well-implemented sort.Interface for key-value pairs.

The pair struct correctly implements sort.Interface to enable sorting of key-value pairs while maintaining their alignment. The implementation is clean and follows Go conventions.


215-238: LGTM: Efficient parameter iteration with proper grouping logic.

The refactored Request.Params() method successfully implements the O(n log n) approach using sorting. The grouping logic correctly:

  • Collects all parameters into the pair struct
  • Sorts by keys to ensure deterministic order
  • Groups consecutive identical keys and yields them as slices
  • Properly handles loop termination with break instead of return

This addresses the performance objectives while maintaining correct functionality.


450-473: LGTM: Consistent implementation for form data iteration.

The Request.AllFormData() method mirrors the same efficient pattern as Request.Params(), providing consistent O(n log n) performance for form data iteration. The implementation correctly uses r.formData.All() as the data source and follows the same proven grouping logic.


323-323: LGTM: Simplified delegation to standard library.

The Request.Cookies() method now correctly delegates to r.cookies.All(), improving code maintainability by eliminating duplicate iteration logic.


362-362: LGTM: Consistent delegation pattern.

The Request.PathParams() method follows the same simplified delegation pattern as cookies, improving consistency across the codebase.


784-784: LGTM: Standard library delegation for map iteration.

The Cookie.All() method now uses maps.All(c) which provides a more idiomatic and potentially optimized iteration approach.


789-789: LGTM: Efficient map clearing.

Using the built-in clear(c) function is more efficient and idiomatic than manual key deletion loops.


832-832: LGTM: Consistent with Cookie.All() implementation.

The PathParam.All() method follows the same pattern as Cookie.All() using maps.All() for consistency.


837-837: LGTM: Efficient clearing consistent with Cookie.Reset().

Using clear(p) provides the same efficiency benefits as the Cookie implementation.

✨ 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
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @ksw2000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on enhancing the performance of several iterator methods within the Request and Response objects by optimizing their time complexity. It also includes refactoring efforts to streamline other iterator and reset methods, making the codebase more efficient and leveraging modern Go language features.

Highlights

  • Performance Optimization: The time complexity for iterator methods Request.Headers(), Request.AllFormData(), and Response.Headers() has been significantly reduced from O(n^2) to O(n log n). This was achieved by collecting all key-value pairs, sorting them, and then iterating, leading to substantial improvements in execution time, memory allocations, and bytes allocated as demonstrated by the provided benchmarks.
  • Behavioral Change for Request.Params(): The Request.Params() method has been updated to iterate over form data (r.formData) instead of its previous parameter source (r.params). This change also incorporates the O(n log n) performance optimization.
  • Code Simplification and Refactoring: The implementations of Request.Cookies(), Request.PathParams(), Cookie.All(), Cookie.Reset(), PathParam.All(), and PathParam.Reset() have been simplified. This was done by directly calling existing helper functions like maps.All() for iteration and utilizing the clear() built-in function for resetting maps, leading to more concise and idiomatic Go code.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request improves iterator performance by reducing time complexity from O(n^2) to O(n log n) for several methods. However, there are a few critical issues related to slice indexing and data sources that need to be addressed to ensure the correctness of the changes. The Request.Params() method was also incorrectly changed to use form data, which needs to be corrected to use query parameters instead.

@ksw2000 ksw2000 marked this pull request as ready for review July 2, 2025 16:41
@ksw2000 ksw2000 requested a review from a team as a code owner July 2, 2025 16:41
@ReneWerner87 ReneWerner87 added this to v3 Jul 2, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Jul 2, 2025
@ReneWerner87 ReneWerner87 merged commit 01d8543 into gofiber:main Jul 2, 2025
12 checks passed
@github-project-automation github-project-automation bot moved this to Done in v3 Jul 2, 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.

2 participants