Skip to content

Improve ConvertToBytes performance#127

Merged
ReneWerner87 merged 7 commits intomasterfrom
codex/2025-07-09-07-57-26
Jul 9, 2025
Merged

Improve ConvertToBytes performance#127
ReneWerner87 merged 7 commits intomasterfrom
codex/2025-07-09-07-57-26

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Jul 9, 2025

Summary

  • optimize numeric parsing in ConvertToBytes
  • replace map lookup with switch for unit multiplier

Testing

  • go vet ./...
  • go test ./...
  • go test -bench=Benchmark_ConvertToBytes -benchmem -run=^$ ./...

https://chatgpt.com/codex/tasks/task_e_686e194510148326b750eb06787f7f5e

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling and parsing of size strings with unit suffixes (e.g., KB, MB, GB, etc.) for more accurate conversions.
  • Refactor

    • Enhanced internal logic for interpreting numeric and unit parts of size strings, resulting in more reliable and consistent behavior.

@ReneWerner87 ReneWerner87 requested a review from a team as a code owner July 9, 2025 07:57
@ReneWerner87 ReneWerner87 requested review from efectn, gaby and sixcolors and removed request for a team July 9, 2025 07:57
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

The ConvertToBytes function in common.go was refactored to improve how it parses size strings with unit suffixes. The numeric part is now parsed as either a float or an unsigned integer based on its format, and the unit multipliers are determined using a switch statement instead of an array lookup. Imports were adjusted accordingly. A new test case was added to common_test.go to verify behavior with invalid unit inputs.

Changes

File(s) Change Summary
common.go Refactored ConvertToBytes: improved numeric parsing, replaced unit lookup with switch, updated imports
common_test.go Added test case in Test_ConvertToBytes for input with invalid unit suffix containing spaces and letters

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ConvertToBytes

    Caller->>ConvertToBytes: Call with human-readable size string
    ConvertToBytes->>ConvertToBytes: Find last numeric character, identify unit
    alt String contains decimal
        ConvertToBytes->>ConvertToBytes: Parse number as float
    else
        ConvertToBytes->>ConvertToBytes: Parse number as uint
    end
    ConvertToBytes->>ConvertToBytes: Switch on unit character for multiplier
    ConvertToBytes-->>Caller: Return computed byte value
Loading

Possibly related PRs

Suggested reviewers

  • gaby
  • efectn

Poem

A nibble, a byte, a gigabyte too,
The function now parses just right for you.
Switches and floats, no more array fright,
Units are handled with code that's light.
With hops and with hops, the rabbit approves—
Your bytes now convert in elegant moves! 🐇✨


📜 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 fb84346 and 78f3247.

📒 Files selected for processing (1)
  • common_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx_test.go:1721-1724
Timestamp: 2024-10-16T12:12:30.506Z
Learning: In the Go unit tests in `ctx_test.go`, it is acceptable to use invalid CIDR notation such as `"0.0.0.1/31junk"` for testing purposes.
common_test.go (13)
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-07-01T15:48:53.094Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:20-23
Timestamp: 2024-07-01T03:44:03.672Z
Learning: Unit tests for key length enforcement in both `EncryptCookie` and `DecryptCookie` functions have been added to ensure robust validation and prevent potential runtime errors.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx_test.go:1721-1724
Timestamp: 2024-10-16T12:12:30.506Z
Learning: In the Go unit tests in `ctx_test.go`, it is acceptable to use invalid CIDR notation such as `"0.0.0.1/31junk"` for testing purposes.
🧬 Code Graph Analysis (1)
common_test.go (1)
common.go (1)
  • ConvertToBytes (117-172)
⏰ 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: Build (1.23.x, windows-latest)
  • GitHub Check: Build (1.24.x, windows-latest)
  • GitHub Check: Compare
🔇 Additional comments (1)
common_test.go (1)

135-135: Good test coverage for invalid unit handling.

This test case effectively validates that the refactored ConvertToBytes function correctly handles malformed input by extracting only the numeric part when encountering invalid unit suffixes. The input "123a k" tests the function's ability to ignore invalid characters ('a') in the unit portion and return just the parsed numeric value.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-07-09-07-57-26

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests 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 or @coderabbitai title 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
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.

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 focuses on enhancing the performance of the ConvertToBytes utility function. The primary goal is to optimize how numeric values are parsed from input strings and to streamline the lookup process for unit multipliers, leading to more efficient byte conversion.

Highlights

  • Performance Optimization: The ConvertToBytes function has been optimized for better performance, particularly in its numeric parsing and unit multiplier handling.
  • Numeric Parsing Improvement: The numeric part of the input string is now parsed more efficiently. It uses strconv.ParseUint for integer values and falls back to strconv.ParseFloat only when a decimal point is detected, avoiding unnecessary floating-point parsing.
  • Unit Multiplier Lookup Refactor: The mechanism for applying unit multipliers (e.g., 'k' for kilo, 'm' for mega) has been refactored from a map-like lookup to a direct switch statement, which typically offers better performance for a fixed set of cases.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.

@codecov
Copy link

codecov bot commented Jul 9, 2025

Codecov Report

Attention: Patch coverage is 93.10345% with 2 lines in your changes missing coverage. Please review.

Project coverage is 96.00%. Comparing base (e4422da) to head (78f3247).
Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
common.go 93.10% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #127      +/-   ##
==========================================
+ Coverage   95.88%   96.00%   +0.11%     
==========================================
  Files           9        9              
  Lines         510      525      +15     
==========================================
+ Hits          489      504      +15     
  Misses         14       14              
  Partials        7        7              
Flag Coverage Δ
unittests 96.00% <93.10%> (+0.11%) ⬆️

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

The pull request improves the performance of the ConvertToBytes function by optimizing numeric parsing and replacing the map lookup with a switch statement for unit multipliers. I've identified a potential issue where the unit prefix position might be set incorrectly if the input string contains non-numeric characters before the unit, and that the switch statement should also handle uppercase prefixes.

@ReneWerner87
Copy link
Member Author

old:

Benchmark_ConvertToBytes/fiber-5                33357991                34.79 ns
/op            0 B/op          0 allocs/op

new:

Benchmark_ConvertToBytes/fiber-5                66803620                18.76 ns
/op            0 B/op          0 allocs/op

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

♻️ Duplicate comments (1)
common.go (1)

129-131: Unit prefix detection logic has a known issue.

The condition c != ' ' will be true for any non-space character, including letters. This means that if the input string contains a mix of numbers and letters before the unit prefix, unitPrefixPos might be set incorrectly. For example, in the string "123a k", unitPrefixPos will be set to the index of 'a' instead of 'k'.

Apply this fix to only detect alphabetic characters as unit prefixes:

-		if c != ' ' {
+		if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
			unitPrefixPos = i
		}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a5704ee and 6bd14c1.

📒 Files selected for processing (1)
  • common.go (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
common.go (5)
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/handlers/books.go:28-43
Timestamp: 2024-11-23T19:54:01.389Z
Learning: In 'clean-code/app/server/handlers/books.go', validation is out of scope and should not be suggested.
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
🪛 GitHub Check: Build (1.24.x, ubuntu-latest)
common.go

[failure] 145-145:
constant -1 overflows uint64

🪛 GitHub Check: Compare
common.go

[failure] 145-145:
constant -1 overflows uint64

🪛 GitHub Actions: Benchmark
common.go

[error] 145-145: Go compiler error: constant -1 overflows uint64

⏰ 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: Analyse
  • GitHub Check: Build (1.23.x, macos-13)
  • GitHub Check: lint
🔇 Additional comments (4)
common.go (4)

16-16: LGTM: Import addition is necessary for the new logic.

The addition of the "strings" package import is required for the strings.IndexByte function used in the conditional parsing logic.


33-35: LGTM: Variable renames are unrelated to the main changes.

These UUID-related variable renames don't affect the ConvertToBytes function optimization.


137-149: Excellent optimization: Conditional parsing improves performance.

The conditional parsing logic that uses strconv.ParseUint for integers and strconv.ParseFloat for decimal values is a smart optimization that avoids unnecessary float parsing overhead for integer inputs.


152-163: LGTM: Switch statement optimization with proper case handling.

The switch statement replacement provides better performance than array lookup. The use of toLowerTable correctly handles both uppercase and lowercase unit prefixes, addressing the previous concern about case sensitivity.

@ReneWerner87
Copy link
Member Author

old:

Benchmark_ConvertToBytes/fiber-12         	57962028	        17.69 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	73125398	        16.58 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	68549522	        16.70 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	70408762	        16.73 ns/op	       0 B/op	       0 allocs/op

new:

Benchmark_ConvertToBytes/fiber-12         	117369555	        10.08 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	100000000	        10.09 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	100000000	        10.30 ns/op	       0 B/op	       0 allocs/op
Benchmark_ConvertToBytes/fiber-12         	100000000	        11.44 ns/op	       0 B/op	       0 allocs/op

@ReneWerner87 ReneWerner87 merged commit c61f118 into master Jul 9, 2025
16 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants