Skip to content

♻️ Refactor: reduce the memory usage of cacheableStatusCodes#3789

Merged
ReneWerner87 merged 1 commit intogofiber:mainfrom
ZihxS:refactor-cacheableStatusCodes
Oct 8, 2025
Merged

♻️ Refactor: reduce the memory usage of cacheableStatusCodes#3789
ReneWerner87 merged 1 commit intogofiber:mainfrom
ZihxS:refactor-cacheableStatusCodes

Conversation

@ZihxS
Copy link
Contributor

@ZihxS ZihxS commented Oct 7, 2025

Description

Replace map[int]bool with map[int]struct{} for the cacheableStatusCodes set.

Why?

map[int]struct{} is the idiomatic Go pattern for representing sets (collections where only key presence matters).
It reduces memory usage slightly by avoiding storage of unnecessary boolean values (struct{} is zero-sized).
Benchmarking confirms:

  • Lower memory footprint (B/op) at scale
  • Same allocation count and runtime performance
  • Clearer intent: emphasizes that we only care about membership, not associated values
package main

import (
	"testing"

	"github.com/gofiber/fiber/v2"
)

const numEntries = 100000 // Try 100, 1000, 10000 to see scaling

var statusCodes = []int{
	fiber.StatusOK,
	fiber.StatusNonAuthoritativeInformation,
	fiber.StatusNoContent,
	fiber.StatusPartialContent,
	fiber.StatusMultipleChoices,
	fiber.StatusMovedPermanently,
	fiber.StatusNotFound,
	fiber.StatusMethodNotAllowed,
	fiber.StatusGone,
	fiber.StatusRequestURITooLong,
	fiber.StatusNotImplemented,
}

func fillMapBool(m map[int]bool) {
	for i := range numEntries {
		code := statusCodes[i%len(statusCodes)]
		m[code+(i/len(statusCodes))*1000] = true
	}
}

func fillMapStruct(m map[int]struct{}) {
	for i := range numEntries {
		code := statusCodes[i%len(statusCodes)]
		m[code+(i/len(statusCodes))*1000] = struct{}{}
	}
}

// BenchmarkMapBool measures map[int]bool allocation
func BenchmarkMapBool(b *testing.B) {
	b.ReportAllocs()
	for b.Loop() {
		m := make(map[int]bool, numEntries)
		fillMapBool(m)
		_ = m
	}
}

// BenchmarkMapStruct measures map[int]struct{} allocation
func BenchmarkMapStruct(b *testing.B) {
	b.ReportAllocs()
	for b.Loop() {
		m := make(map[int]struct{}, numEntries)
		fillMapStruct(m)
		_ = m
	}
}

Custom Demo Benchmark:
Screenshot 2025-10-08 at 06 25 32

Bencmark_Cache (BEFORE):
Screenshot 2025-10-08 at 06 27 35

Bencmark_Cache (AFTER):
Screenshot 2025-10-08 at 06 28 58

Impact:

  • No functional or behavioral changes
  • Fully backward-compatible
  • Aligns codebase with Go best practices
  • This is a small, safe cleanup that improves code clarity and efficiency.

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.

  • 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

@ZihxS ZihxS requested a review from a team as a code owner October 7, 2025 23:32
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 7, 2025

Walkthrough

Replaced a map[int]bool with map[int]struct{} for cacheable HTTP status codes in middleware/cache/cache.go and updated lookup logic to use presence checks. Status code set remains unchanged; only the data structure and access pattern were modified.

Changes

Cohort / File(s) Summary of changes
Cache status set refactor
middleware/cache/cache.go
Switched cacheableStatusCodes from map[int]bool to map[int]struct{}; updated literals (true → {}); changed condition to presence check using comma-ok idiom without altering the set of cacheable codes.

Sequence Diagram(s)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

🧹 Updates, ⚡️ Performance

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn
  • gaby

Poem

I nibbled maps of codes so neat,
Swapped bools for structs—less memory to eat.
The cache still hops on status cues,
Same garden path, just lighter shoes.
Thump-thump! I optimize, then scoot—
A tidy warren, swift and cute. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly captures the main change by highlighting a refactor to reduce the memory usage of cacheableStatusCodes, making the primary intent immediately clear to reviewers.
Description Check ✅ Passed The description aligns with the repository template by including separate Description, Changes introduced, Type of change, and Checklist sections and provides a clear purpose, rationale, benchmarks, and examples that illustrate the memory usage improvements while emphasizing backward compatibility and code clarity.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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 2ebd143 and 0466ee0.

📒 Files selected for processing (1)
  • middleware/cache/cache.go (2 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:

  • middleware/cache/cache.go
🧬 Code graph analysis (1)
middleware/cache/cache.go (1)
constants.go (11)
  • StatusOK (52-52)
  • StatusNonAuthoritativeInformation (55-55)
  • StatusNoContent (56-56)
  • StatusPartialContent (58-58)
  • StatusMultipleChoices (63-63)
  • StatusMovedPermanently (64-64)
  • StatusNotFound (77-77)
  • StatusMethodNotAllowed (78-78)
  • StatusGone (83-83)
  • StatusRequestURITooLong (87-87)
  • StatusNotImplemented (104-104)
⏰ 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). (4)
  • GitHub Check: Compare
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: repeated
🔇 Additional comments (3)
middleware/cache/cache.go (3)

55-67: LGTM! Idiomatic Go set representation with reduced memory footprint.

The refactor from map[int]bool to map[int]struct{} is the standard Go idiom for representing sets. Since struct{} occupies zero bytes, this change reduces memory usage while maintaining the same functionality. All status code entries are correctly converted from true to {}.


240-240: LGTM! Correct presence check for the refactored map.

The lookup correctly uses the comma-ok idiom to check for presence in the map[int]struct{}. The logic is preserved: if the status code is not present in cacheableStatusCodes, the response is marked as unreachable.


55-67: Confirmed no additional references to cacheableStatusCodes; no further changes required.
Search results show only its declaration and usage in cache.go.


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
Contributor

Summary of Changes

Hello @ZihxS, 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 refactors the cacheableStatusCodes map within the caching middleware to use map[int]struct{} instead of map[int]bool. This change is a performance improvement aimed at reducing memory consumption by utilizing a zero-sized struct for set elements, which is the idiomatic Go approach for representing sets. The refactoring also enhances code clarity and maintains full backward compatibility.

Highlights

  • Memory Optimization: Replaced map[int]bool with map[int]struct{} for the cacheableStatusCodes variable to reduce memory usage, leveraging the idiomatic Go pattern for representing sets.
  • Code Clarity and Best Practices: The change improves code clarity by explicitly indicating that only key presence matters, aligning the codebase with Go's best practices for set implementation.
  • Performance and Compatibility: Benchmarking confirms a lower memory footprint without impacting runtime performance or allocation count. The refactoring is fully backward-compatible with no functional or behavioral changes.
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
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 is an excellent pull request that refactors cacheableStatusCodes to use the idiomatic Go pattern map[int]struct{} for representing a set. This change correctly reduces memory usage and improves code clarity by signaling that only key presence matters. The logic for checking status code cacheability has been updated appropriately. The pull request description is very clear and includes benchmark results to support the change. The implementation is correct and follows best practices. I have no further suggestions; great work!

@codecov
Copy link

codecov bot commented Oct 7, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.67%. Comparing base (2ebd143) to head (0466ee0).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #3789   +/-   ##
=======================================
  Coverage   91.67%   91.67%           
=======================================
  Files         113      113           
  Lines       11959    11959           
=======================================
  Hits        10964    10964           
  Misses        731      731           
  Partials      264      264           
Flag Coverage Δ
unittests 91.67% <100.00%> (ø)

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.

@ReneWerner87 ReneWerner87 added this to v3 Oct 8, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Oct 8, 2025
@ReneWerner87 ReneWerner87 merged commit 6718141 into gofiber:main Oct 8, 2025
15 of 16 checks passed
@github-project-automation github-project-automation bot moved this to Done in v3 Oct 8, 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