Skip to content

perf: preallocate slice size in Client::Param()#3782

Merged
gaby merged 3 commits intogofiber:mainfrom
arturmelanchyk:slice-prealloc
Oct 5, 2025
Merged

perf: preallocate slice size in Client::Param()#3782
gaby merged 3 commits intogofiber:mainfrom
arturmelanchyk:slice-prealloc

Conversation

@arturmelanchyk
Copy link
Contributor

Description

Tiny improvement

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

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.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@arturmelanchyk arturmelanchyk marked this pull request as ready for review October 5, 2025 13:07
@arturmelanchyk arturmelanchyk requested a review from a team as a code owner October 5, 2025 13:07
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 5, 2025

Walkthrough

Preallocate result slices in three client functions to set capacity from the number of retrieved values before appending, without changing return values or control flow.

Changes

Cohort / File(s) Summary
Slice preallocation optimization
client/client.go, client/request.go
Replace nil or []string{}-initialized result slices with make([]string, 0, len(tmp)) to preallocate capacity matching the number of retrieved values (used by Param/FormData/Param variants). No API, return value, or control-flow changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested labels

⚡️ Performance

Suggested reviewers

  • gaby
  • sixcolors
  • ReneWerner87
  • efectn

Poem

I hop through code with whiskers bright,
I set some space before the write.
No extra grows, just tidy stacks,
Appends stride forward, no fallback tracks.
A tiny tweak — the sprint feels light 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description only contains the phrase “Tiny improvement” followed by an unmodified template checklist and lacks any summary of the actual code changes, motivation, performance impact, benchmarks, documentation updates, or changelog entries. Expand the description to detail the specific slice preallocation changes, explain the performance benefits, and complete the template sections with relevant benchmarks, documentation updates, changelog entries, and any necessary examples or migration guidance.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title clearly indicates a performance optimization by preallocating slice capacity in the Client::Param() method, which aligns with a central change introduced in this PR. Although related slice preallocation changes in FormData are not mentioned, the title remains specific and concise about the primary improvement.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 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 ff8d323 and 8f9511d.

📒 Files selected for processing (1)
  • client/request.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/request.go
⏰ 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, macos-13)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare

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.

@codecov
Copy link

codecov bot commented Oct 5, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.62%. Comparing base (a3c54bb) to head (8f9511d).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3782      +/-   ##
==========================================
- Coverage   91.67%   91.62%   -0.06%     
==========================================
  Files         113      113              
  Lines       11959    11959              
==========================================
- Hits        10964    10958       -6     
- Misses        731      736       +5     
- Partials      264      265       +1     
Flag Coverage Δ
unittests 91.62% <100.00%> (-0.06%) ⬇️

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
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

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

LGTM

@gaby gaby added 🧹 Updates v3 hacktoberfest 🚀 Open for Hacktoberfest contributions! labels Oct 5, 2025
Signed-off-by: Artur Melanchyk <13834276+arturmelanchyk@users.noreply.github.com>
Copy link
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: 0

🧹 Nitpick comments (2)
client/request.go (2)

211-217: Consider applying the same preallocation pattern for consistency.

The Param method uses the same pattern as FormData but doesn't preallocate the result slice. For consistency with the optimization applied in this PR, consider applying the same change here:

 func (r *Request) Param(key string) []string {
-	var res []string
 	tmp := r.params.PeekMulti(key)
+	res := make([]string, 0, len(tmp))
 	for _, v := range tmp {
 		res = append(res, utils.UnsafeString(v))
 	}
 	return res
 }

710-719: Optional: Consider preallocating with estimated capacity.

While PeekMultiple cannot preallocate the exact capacity (since it filters by key), you could provide an initial capacity hint to reduce early reallocations:

 func (h *Header) PeekMultiple(key string) []string {
-	var res []string
+	res := make([]string, 0, 4) // reasonable initial capacity
 	byteKey := []byte(key)
 	for k, value := range h.RequestHeader.All() {
 		if bytes.EqualFold(k, byteKey) {
 			res = append(res, utils.UnsafeString(value))
 		}
 	}
 	return res
 }

Note: This is a minor optimization since the exact count is unknown upfront.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b1f906e and ff8d323.

📒 Files selected for processing (1)
  • client/request.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • client/request.go
⏰ 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). (3)
  • GitHub Check: Compare
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
🔇 Additional comments (1)
client/request.go (1)

449-456: LGTM! Good optimization.

The preallocation correctly sizes the result slice capacity to match the number of values, avoiding reallocation during the append loop. This is a clean performance improvement with no behavior change.

Signed-off-by: Artur Melanchyk <13834276+arturmelanchyk@users.noreply.github.com>
@gaby gaby added this to v3 Oct 5, 2025
@gaby gaby added this to the v3 milestone Oct 5, 2025
@gaby gaby requested a review from Copilot October 5, 2025 16:15
Copy link
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 improves performance by preallocating slice capacity in three methods that return query parameter and form data values. The optimization prevents multiple memory reallocations during slice growth by setting the initial capacity to match the expected number of elements.

  • Preallocated slice capacity in Client.Param() method
  • Preallocated slice capacity in Request.Param() method
  • Preallocated slice capacity in Request.FormData() method

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
client/client.go Updated Client.Param() to preallocate slice with capacity based on tmp length
client/request.go Updated Request.Param() and Request.FormData() methods to preallocate slices with capacity based on tmp length

@gaby gaby merged commit ff4da56 into gofiber:main Oct 5, 2025
15 checks passed
@github-project-automation github-project-automation bot moved this to Done in v3 Oct 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberfest 🚀 Open for Hacktoberfest contributions! 🧹 Updates v3

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants