Skip to content

♻️ refactor: Improve performance (reduce allocations)#3964

Merged
ReneWerner87 merged 5 commits into
mainfrom
optimizations-1
Dec 24, 2025
Merged

♻️ refactor: Improve performance (reduce allocations)#3964
ReneWerner87 merged 5 commits into
mainfrom
optimizations-1

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

No description provided.

Copilot AI review requested due to automatic review settings December 24, 2025 10:08
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner December 24, 2025 10:08
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 24, 2025

Warning

Rate limit exceeded

@ReneWerner87 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 18 minutes and 23 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 370d3ad and 94f7acb.

📒 Files selected for processing (1)
  • res.go

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Centralized Cache-Control directive detection; reduced repeated string conversions in route pattern matching; adjusted flash-message zero-values and query building; added slice/map preallocation across helpers; switched some response builders to byte-buffer writes to lower allocations.

Changes

Cohort / File(s) Summary
Cache Directive Detection
middleware/cache/cache.go
Added hasDirective(cc, directive string) bool for case-insensitive, token-boundary-aware Cache-Control parsing; hasRequestDirective() and no-store checks delegate to it.
Routing Optimization
path.go
RoutePatternMatch() computes patternStr once and reuses it for parsing and wildcard checks (avoids repeated conversions).
Redirect / Flash behavior
redirect.go
Messages() returns nil when empty; OldInputs() precounts and preallocates or returns nil; query-string construction simplified to avoid index-based separators.
Allocation / Preallocation
state.go, helpers.go, hooks.go, middleware/logger/tags.go
Added capacity hints and reuse of computed keys: Keys(), serviceKeys(), Services() map capacity; UniqueRouteStack preallocates map/slice; PreStartupMessageData.addEntry preallocates entries; TagReqHeaders adjusts allocations.
Response helpers
res.go
JSONP payload built via byte-buffer writes and SetBodyRaw; Link header constructed via incremental writes to reduce concatenation allocations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

⚡️ Performance

Suggested reviewers

  • sixcolors
  • efectn
  • gaby

Poem

🐇 I checked each header, light and spry,
Reused a string and let others fly,
Slices found rooms where they once squeezed,
Flashes tidy, queries eased,
A little hop — the build runs spry 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided by the author, violating the repository's required description template which specifies sections for purpose, changes, type, and checklist items. Add a comprehensive description covering the problem addressed, specific optimizations made in each file, performance benchmarks, and confirmation that checklist items (tests, documentation, performance goals) have been completed.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: refactoring code to improve performance by reducing allocations across multiple files.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @ReneWerner87, 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 introduces targeted improvements to both the caching middleware's Cache-Control header processing and general memory management practices. The changes aim to enhance the efficiency of directive parsing and significantly reduce memory footprint by optimizing slice allocations and string conversions across various utility functions, contributing to a more performant application.

Highlights

  • Cache-Control Directive Handling Refactor: The logic for parsing and checking Cache-Control directives within the caching middleware has been refactored into a more generic and efficient hasDirective function, improving reusability and performance.
  • Memory Allocation Optimizations: Several optimizations have been implemented across path.go, redirect.go, and state.go to reduce memory allocations. This includes avoiding the creation of empty slices by returning nil and pre-allocating slice capacities where the size can be estimated or is known.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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
Copy Markdown
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

This pull request introduces several valuable optimizations and refactorings. The handling of cache-control directives is now more robust and efficient, thanks to a new hasDirective function that avoids unnecessary allocations and correctly identifies directives. Memory allocation optimizations are applied across different files, including pre-allocating slices in redirect.go and state.go, and reducing []byte to string conversions in path.go. Additionally, the changes in redirect.go to return nil for empty slices align with idiomatic Go practices. While the changes are positive, I've identified a potential correctness issue in state.go where iterating over keys could terminate prematurely, and I've provided suggestions to address it.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 24, 2025

Codecov Report

❌ Patch coverage is 93.18182% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.59%. Comparing base (032ff5f) to head (94f7acb).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
redirect.go 80.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3964      +/-   ##
==========================================
- Coverage   91.67%   91.59%   -0.09%     
==========================================
  Files         119      119              
  Lines       10177    10194      +17     
==========================================
+ Hits         9330     9337       +7     
- Misses        536      543       +7     
- Partials      311      314       +3     
Flag Coverage Δ
unittests 91.59% <93.18%> (-0.09%) ⬇️

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.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR refactors cache-control directive handling and optimizes memory allocations across multiple files to improve performance and code maintainability.

  • Introduced a reusable hasDirective function for proper cache-control directive parsing with boundary checking
  • Pre-allocated slices with estimated capacity to reduce memory allocations
  • Optimized string conversions by caching the result in variables
  • Changed empty slice returns to nil for better idiomatic Go code

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
middleware/cache/cache.go Refactored cache-control directive checking by extracting a reusable hasDirective function with proper boundary validation, replacing the previous strings.Contains approach that could have false positives
state.go Added pre-allocation with capacity 8 to slice initialization in Keys() and serviceKeys() methods to reduce memory allocations during iteration
redirect.go Changed empty slice returns to nil, added early return optimization in OldInputs(), and pre-allocated the inputs slice with capacity based on flash messages length
path.go Cached the string(patternPretty) conversion in a patternStr variable to avoid repeated conversions in the wildcard matching logic

Comment thread redirect.go Outdated
Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 5f73079 Previous: 032ff5f Ratio
Benchmark_Ctx_Write 29.75 ns/op 73 B/op 0 allocs/op 17.14 ns/op 65 B/op 0 allocs/op 1.74
Benchmark_Ctx_Write - ns/op 29.75 ns/op 17.14 ns/op 1.74

This comment was automatically generated by workflow using github-action-benchmark.

@ReneWerner87 ReneWerner87 changed the title ♻️ refactor: Improve cache-control directive handling and optimize memory allocations ♻️ refactor: Improve performance (reduce allocations) Dec 24, 2025
Copy link
Copy Markdown
Contributor

@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: 1

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0bfb4c and 36d302e.

📒 Files selected for processing (2)
  • redirect.go
  • res.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • redirect.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

Prefer github.com/gofiber/utils/v2 helpers (for example, utils.Trim) when performing common operations such as string manipulation, whenever it is practical and appropriate for the surrounding code

Files:

  • res.go
🧬 Code graph analysis (1)
res.go (1)
constants.go (2)
  • HeaderXContentTypeOptions (246-246)
  • MIMETextJavaScriptCharsetUTF8 (36-36)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: repeated
  • GitHub Check: lint
  • GitHub Check: Compare
🔇 Additional comments (1)
res.go (1)

572-574: LGTM: Efficient buffer writes without string concatenation.

Splitting the rel attribute construction into separate WriteString calls avoids the intermediate allocation from string concatenation. This aligns well with the PR's optimization goals.

Comment thread res.go
@ReneWerner87
Copy link
Copy Markdown
Member Author

/gemini review

Copy link
Copy Markdown
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

This pull request introduces a series of performance optimizations across the codebase, primarily focused on reducing memory allocations. The changes are well-implemented and follow common Go performance idioms. Key improvements include pre-allocating slices and maps with known capacities, replacing string concatenations with more efficient buffer writes, and avoiding repeated computations within loops. These refactorings enhance efficiency without altering functionality. Overall, this is a solid contribution to improving the framework's performance.

@ReneWerner87 ReneWerner87 merged commit 93830f2 into main Dec 24, 2025
15 checks passed
@ReneWerner87 ReneWerner87 deleted the optimizations-1 branch December 24, 2025 11:45
@github-project-automation github-project-automation Bot moved this to Done in v3 Dec 24, 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