Skip to content

♻️ Refactor: replace isInCharset with bytes.IndexByte#3342

Merged
ReneWerner87 merged 1 commit intogofiber:mainfrom
ksw2000:remove-isInCharset
Mar 7, 2025
Merged

♻️ Refactor: replace isInCharset with bytes.IndexByte#3342
ReneWerner87 merged 1 commit intogofiber:mainfrom
ksw2000:remove-isInCharset

Conversation

@ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Mar 7, 2025

Description

The standard library bytes already includes bytes.IndexByte, which is implemented in assembly language. Its performance is superior to ours. Additionally, replacing isInCharset with the standard library function can reduce maintenance costs.

func BenchmarkIsInCharset(b *testing.B) {
	t := []byte("hello, world!")
	for i := 0; i < b.N; i++ {
		_ = isInCharset('!', t)
		_ = isInCharset(',', t)
		_ = isInCharset('w', t)
		_ = isInCharset('a', t)
		_ = isInCharset('b', t)
		_ = isInCharset('c', t)
	}
}
func BenchmarkIsInCharset(b *testing.B) {
	t := []byte("hello, world!")
	for i := 0; i < b.N; i++ {
		_ = bytes.IndexByte(t, '!') != -1
		_ = bytes.IndexByte(t, ',') != -1
		_ = bytes.IndexByte(t, 'w') != -1
		_ = bytes.IndexByte(t, 'a') != -1
		_ = bytes.IndexByte(t, 'b') != -1
		_ = bytes.IndexByte(t, 'c') != -1
	}
}

Benchmark test result

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 7763 64-Core Processor                
              │   ori.txt   │               std.txt               │
              │   sec/op    │   sec/op     vs base                │
IsInCharset-4   36.97n ± 3%   19.39n ± 1%  -47.55% (p=0.000 n=25)

Type of change

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes update the character checking logic in two files by replacing a custom function with a standard library call. In ctx.go, the getLocationFromRoute method now uses bytes.IndexByte instead of isInCharset to verify if a parameter key is "greedy". In path.go, the custom isInCharset function has been removed and its usage in analyseParameterPart has been replaced with bytes.IndexByte for checking parameter delimiters, while keeping the overall control flow intact.

Changes

File(s) Change Summary
ctx.go Modified the getLocationFromRoute method in the DefaultCtx struct by replacing the isInCharset function call with bytes.IndexByte, keeping the greedy parameter check logic intact.
path.go Removed the isInCharset function and updated the analyseParameterPart method to use bytes.IndexByte for verifying delimiter characters.

Possibly related PRs

Suggested labels

🧹 Updates, v3

Suggested reviewers

  • sixcolors
  • efectn
  • gaby
  • ReneWerner87

Poem

I'm a little rabbit with a coding delight,
Hopping through bytes from morning till night.
Goodbye old checks, hello speed so bright,
With IndexByte in place, everything's just right.
I nibble these changes with a happy byte! 🐰

✨ 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.
    • 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 generate docstrings to generate docstrings for 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.

@codecov
Copy link

codecov bot commented Mar 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.66%. Comparing base (4177ab4) to head (9090652).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3342      +/-   ##
==========================================
+ Coverage   83.63%   83.66%   +0.03%     
==========================================
  Files         118      118              
  Lines       11717    11711       -6     
==========================================
- Hits         9799     9798       -1     
+ Misses       1489     1485       -4     
+ Partials      429      428       -1     
Flag Coverage Δ
unittests 83.66% <100.00%> (+0.03%) ⬆️

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 7, 2025 13:25
@ksw2000 ksw2000 requested a review from a team as a code owner March 7, 2025 13:25
@ksw2000 ksw2000 requested review from ReneWerner87, efectn, gaby and sixcolors and removed request for a team March 7, 2025 13:25
@gaby gaby added this to the v3 milestone Mar 7, 2025
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 (1)
ctx.go (1)

1352-1352: Performance improvement using bytes.IndexByte

The change from isInCharset to bytes.IndexByte is a good optimization. The bytes.IndexByte function is implemented in assembly language, which provides better performance than the custom implementation.

Consider adding a comment explaining that this is an optimized version using assembly-based implementation, which helps future developers understand the performance implications of this code.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4177ab4 and 9090652.

📒 Files selected for processing (2)
  • ctx.go (1 hunks)
  • path.go (2 hunks)
🔇 Additional comments (2)
path.go (2)

9-10: Added bytes package import

Adding the bytes package import is necessary for using the bytes.IndexByte function as a replacement for the removed isInCharset function.


312-312:

Details

✅ Verification successful

Improved performance by replacing isInCharset with bytes.IndexByte

Replacing the custom isInCharset function with the standard library bytes.IndexByte function is a good optimization. The standard library function is implemented in assembly language, offering better performance.


🏁 Script executed:

#!/bin/bash
# Benchmark the performance improvement of bytes.IndexByte vs the old implementation

# Look for any remaining instances of isInCharset that might need to be replaced
echo "Checking for any remaining isInCharset instances in the codebase:"
rg -A 3 "isInCharset" || echo "No instances found, all have been replaced."

# Find functions similar to isInCharset that might benefit from this optimization pattern
echo "Finding similar functions that might benefit from the same optimization:"
rg -A 5 "func.*\(\s*char\s+byte\s*,\s*charset\s+\[\]byte\s*\)"

Length of output: 479


Performance improvement verified: The replacement of the custom isInCharset function with bytes.IndexByte is confirmed to be effective. Our search shows that no remaining references to isInCharset exist in the codebase, and no similar functions were identified that might benefit from further optimization.

  • The change at path.go, line 312, is correctly implemented.
  • No additional actions or changes are required.

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

👍 LGTM

@ReneWerner87 ReneWerner87 added this to v3 Mar 7, 2025
@ReneWerner87 ReneWerner87 merged commit 600ebd9 into gofiber:main Mar 7, 2025
18 of 19 checks passed
@github-project-automation github-project-automation bot moved this to Done in v3 Mar 7, 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.

3 participants