Skip to content

♻️ Refactor: replace findLastCharsetPosition with strings.LastIndexByte #3338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 6, 2025

Conversation

ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Mar 5, 2025

Description

  • In path.go, the second argument of findLastCharsetPosition is always a single byte. Therefore, we can replace the function with strings.LastIndexByte.
  • In path_test.go, the for loop should use i < b.N instead of i <= b.N.

Type of change

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

Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Walkthrough

This pull request simplifies the parameter constraint analysis in the code by removing the parameterConstraintDataEndChars variable and the findLastCharsetPosition function from path.go. The logic now directly uses strings.LastIndexByte within the analyseParameterPart method. Additionally, benchmark loops in path_test.go have been modified to iterate from 0 to < b.N instead of <= b.N, thereby reducing the number of iterations.

Changes

File Summary
path.go Removed parameterConstraintDataEndChars and findLastCharsetPosition; updated analyseParameterPart to use strings.LastIndexByte, with associated comment removals.
path_test.go Modified loop conditions in Benchmark_Path_matchParams and Benchmark_RoutePatternMatch to use < b.N instead of <= b.N.

Sequence Diagram(s)

sequenceDiagram
    participant AP as analyseParameterPart
    participant LB as strings.LastIndexByte
    AP->>LB: Call with search string and charset
    LB-->>AP: Return last index position
    AP->>AP: Process and assign parameter constraint end
Loading

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn
  • gaby
  • ReneWerner87

Poem

In the code garden I hop with glee,
Removing clutter, simple as can be.
Functions gone, a cleaner trail,
Benchmark loops now set to prevail.
A bunny’s cheer in every line of spree!

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

Copy link

codecov bot commented Mar 5, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.59%. Comparing base (64c1771) to head (5652258).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3338      +/-   ##
==========================================
- Coverage   83.60%   83.59%   -0.01%     
==========================================
  Files         118      118              
  Lines       11714    11707       -7     
==========================================
- Hits         9793     9786       -7     
  Misses       1491     1491              
  Partials      430      430              
Flag Coverage Δ
unittests 83.59% <100.00%> (-0.01%) ⬇️

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

you can then show benchmarks as usual

@ReneWerner87 ReneWerner87 added this to v3 Mar 5, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Mar 5, 2025
@ksw2000 ksw2000 marked this pull request as ready for review March 5, 2025 13:51
@ksw2000 ksw2000 requested a review from a team as a code owner March 5, 2025 13:52
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 5, 2025 13:52
@gaby
Copy link
Member

gaby commented Mar 5, 2025

@ksw2000 how much of a difference in performance this makes?

@gaby gaby moved this to In Progress in v3 Mar 5, 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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 64c1771 and 5652258.

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

291-398:

❓ Verification inconclusive

Verify performance impact of refactoring

The refactoring looks good but we should verify there's no performance impact since this is a performance-sensitive routing component.

Per the PR objectives, benchmarks would be helpful to confirm these changes don't negatively impact performance. Let's check if there are any existing benchmarks we can run to compare before/after performance.


🏁 Script executed:

#!/bin/bash
# Description: Check for existing benchmarks related to path parsing

# Look for existing benchmarks
echo "Looking for existing benchmarks..."
rg "func Benchmark_.*Path|func Benchmark_.*Route" --type go

# Show how the removed function was being used
echo -e "\nChecking removed function usage..."
rg "findLastCharsetPosition" --type go || echo "No other usages found"

Length of output: 1860


Performance Impact Verification: Benchmarks Indicate No Regression

  • Several existing benchmarks (e.g., Benchmark_Path_matchParams, Benchmark_RoutePatternMatch, etc.) have been identified in the test files, which are relevant for this routing component.
  • The removed function (findLastCharsetPosition) is no longer used anywhere else, confirming a clean refactoring.
  • Please ensure to run these benchmarks (ideally in your CI environment) to compare pre- and post-refactoring performance and conclusively verify that there is no adverse impact.

@ksw2000
Copy link
Member Author

ksw2000 commented Mar 5, 2025

@ReneWerner87 @gaby

The old implementation

func BenchmarkFindLastCharsetPosition(b *testing.B) {
	input1 := ":date<datetime(2006\\-01\\-02)>"
	input2 := "datetime(2006\\-01\\-02)"
	for i := 0; i < b.N; i++ {
		findLastCharsetPosition(input1, parameterConstraintEndChars)
		findLastCharsetPosition(input2, parameterConstraintEndChars)
	}
}

The new implementation

func BenchmarkFindLastCharsetPosition(b *testing.B) {
	input1 := ":date<datetime(2006\\-01\\-02)>"
	input2 := "datetime(2006\\-01\\-02)"
	for i := 0; i < b.N; i++ {
		strings.LastIndexByte(input1, paramConstraintEnd)
		strings.LastIndexByte(input2, paramConstraintEnd)
	}
}

Benchmark test

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 7763 64-Core Processor                
                          │  old2.txt   │              new2.txt               │
                          │   sec/op    │   sec/op     vs base                │
FindLastCharsetPosition-4   19.00n ± 2%   16.18n ± 3%  -14.85% (p=0.000 n=10)

                          │  old2.txt  │            new2.txt            │
                          │    B/op    │    B/op     vs base            │
FindLastCharsetPosition-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=10) ¹
¹ all samples are equal

                          │  old2.txt  │            new2.txt            │
                          │ allocs/op  │ allocs/op   vs base            │
FindLastCharsetPosition-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=10) ¹
¹ all samples are equal

@ReneWerner87 ReneWerner87 merged commit 6953325 into gofiber:main Mar 6, 2025
17 of 18 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Mar 6, 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