perf(handler): replace fmt.Sprintf with precomputed const strings in validatePassword#172
Merged
veverkap merged 2 commits intoMay 3, 2026
Conversation
…validatePassword
The two fmt.Sprintf calls in validatePassword were computing identical
strings on every failed password validation attempt:
fmt.Sprintf("password must be at least %d bytes", minPasswordLength)
fmt.Sprintf("password must be at most %d bytes", maxPasswordLength)
Both minPasswordLength (8) and maxPasswordLength (72) are compile-time
constants, so the resulting strings never vary. Replace them with
package-level const strings (errPasswordTooShort, errPasswordTooLong)
evaluated once at compile time.
This also allows removing the fmt import from handler/helpers.go
entirely, as it was used only in validatePassword.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2 tasks
Contributor
There was a problem hiding this comment.
Pull request overview
This PR optimizes the password validation error path in handler.validatePassword by removing per-call fmt.Sprintf usage and replacing it with precomputed string constants, allowing the fmt import to be dropped from handler/helpers.go.
Changes:
- Remove
fmtimport fromhandler/helpers.go. - Add precomputed error message constants for too-short / too-long password cases.
- Update
validatePasswordto use the precomputed constants instead offmt.Sprintf.
Show a summary per file
| File | Description |
|---|---|
| handler/helpers.go | Replaces formatted error strings with precomputed constants and removes the unused fmt import. |
Copilot's findings
Tip
Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Files reviewed: 1/1 changed files
- Comments generated: 2
…init time Replace literal string constants for errPasswordTooShort/errPasswordTooLong with package-level vars initialized via fmt.Sprintf from minPasswordLength/ maxPasswordLength. This eliminates the silent drift risk (where updating a length constant would leave error messages reporting stale numbers) while preserving the single-allocation-at-startup property. Also corrects the code comment: the optimization avoids per-call fmt.Sprintf allocations, not all allocations on the error path.
github-actions Bot
added a commit
that referenced
this pull request
May 3, 2026
PR #172 merged the error strings as package-level var initialised via fmt.Sprintf at init time. This follow-up converts them to true compile-time const literals and removes the now-unused fmt import. - errPasswordTooShort and errPasswordTooLong are now immutable const strings - fmt import removed from handler/helpers.go - Both const declarations merged into the existing minPasswordLength block Proxy metric: heap allocations per validatePassword call. Before: 0 allocs (fmt.Sprintf ran once at init, not per call). After: 0 allocs AND strings are immutable, with no fmt overhead at init. Bonus: fmt package no longer imported → slightly smaller binary init. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This was referenced May 3, 2026
veverkap
added a commit
that referenced
this pull request
May 7, 2026
…port (#211) * perf(handler): convert password error vars to const; remove fmt import PR #172 merged the error strings as package-level var initialised via fmt.Sprintf at init time. This follow-up converts them to true compile-time const literals and removes the now-unused fmt import. - errPasswordTooShort and errPasswordTooLong are now immutable const strings - fmt import removed from handler/helpers.go - Both const declarations merged into the existing minPasswordLength block Proxy metric: heap allocations per validatePassword call. Before: 0 allocs (fmt.Sprintf ran once at init, not per call). After: 0 allocs AND strings are immutable, with no fmt overhead at init. Bonus: fmt package no longer imported → slightly smaller binary init. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * docs(handler): add sync comment for password error string constants The numeric literals in errPasswordTooShort and errPasswordTooLong must stay aligned with minPasswordLength and maxPasswordLength; add a comment making that coupling explicit. --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Patrick Veverka <veverkap@users.noreply.github.com>
1 task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🤖 Daily Efficiency Improver — automated AI assistant focused on reducing energy consumption and computational footprint.
Goal and Rationale
validatePasswordinhandler/helpers.gocalledfmt.Sprintftwice on every failed password validation attempt, despite deriving from compile-time constants:fmt.Sprintf("password must be at least %d bytes", minPasswordLength)fmt.Sprintf("password must be at most %d bytes", maxPasswordLength)Since
minPasswordLength = 8andmaxPasswordLength = 72are untyped integer constants, the results never vary across the program's lifetime. Replacing them with compile-timeconststrings eliminates both allocations entirely. As a bonus, thefmtimport inhandler/helpers.gois no longer needed and is removed.Focus Area
Code-Level Efficiency — eliminate unnecessary per-call string allocations on the password validation error path.
Approach
Add two
conststring values to the existingconstblock alongsideminPasswordLengthandmaxPasswordLength:Replace the two
fmt.Sprintfcallsites with direct references to these constants, and remove the now-unusedfmtimport.Energy Efficiency Evidence
Proxy metric: heap allocation count and size at password validation failure time.
fmt.Sprintfallocs per short-password failurefmt.Sprintfallocs per long-password failureMeasurement methodology: static analysis.
fmt.Sprintfallocates a new string on every call;minPasswordLength/maxPasswordLengthare compile-time constants so the result never varies. The string constants reside in the read-only data segment and are referenced at zero cost.*Link to energy: fewer heap allocations → less GC pressure → fewer GC pause cycles → lower CPU energy per failed signup/changePassword/resetPassword request. The absolute savings per call are small (error path only), but the change is zero-risk and consistent with the series of precomputed constant optimisations already applied across the codebase.
Green Software Foundation Context
Hardware Efficiency: Amortising fixed work (format-string evaluation) to program start time rather than per-request time is a direct application of the hardware-efficiency principle — don't burn CPU computing the same result repeatedly.
Trade-offs
errPasswordTooShort,errPasswordTooLong) are self-documenting and placed immediately adjacent tominPasswordLength/maxPasswordLength, so the relationship is clear.constblock and the comment explicitly states this relationship, making accidental drift unlikely.Reproducibility
Test Status
Build and tests cannot be validated locally —
proxy.golang.orgis blocked by the network firewall in this sandbox (consistent with all previous runs). The change is syntactically trivial (two const additions, two call-site substitutions, one import removal). CI should confirm correctness.This PR continues the series of compile-time constant precomputation optimisations: #55 (totpFormat), #82 (totpEncoding), #170 (totpDigitsStr/totpPeriodStr/totpHandlerEncoding).
Warning
The following domain was blocked by the firewall during workflow execution:
proxy.golang.orgTo allow these domains, add them to the
network.allowedlist in your workflow frontmatter:See Network Configuration for more information.
Note
🔒 Integrity filter blocked 1 item
The following item were blocked because they don't meet the GitHub integrity level.
search_pull_requests: has lower integrity than agent requires. The agent cannot read data with integrity below "approved".To allow these resources, lower
min-integrityin your GitHub frontmatter:Greptile Summary
This PR moves the two
fmt.Sprintfcalls invalidatePasswordto package-level initialization to avoid per-call allocations on the error path. The implementation diverges from the PR description: it usesvar(notconst) and retains thefmtimport rather than removing it.Confidence Score: 5/5
Safe to merge; the only finding is a P2 style/best-practice concern about var vs const.
No P0 or P1 findings. The single comment is P2: the error strings are declared as mutable var instead of immutable const, and the fmt import is not removed as the description claims. Functionally the change is correct.
handler/helpers.go — var vs const choice for errPasswordTooShort/errPasswordTooLong.
Important Files Changed
Flowchart
%%{init: {'theme': 'neutral'}}%% flowchart TD A[HTTP Request] --> B[validatePassword] B --> C{len < minPasswordLength?} C -- Yes --> D[writeError with errPasswordTooShort\npackage-level var] C -- No --> E{len > maxPasswordLength?} E -- Yes --> F[writeError with errPasswordTooLong\npackage-level var] E -- No --> G[return true] D --> H[return false] F --> H subgraph PackageInit["Package Init (once at startup)"] I["errPasswordTooShort = fmt.Sprintf(...)"] J["errPasswordTooLong = fmt.Sprintf(...)"] end PackageInit --> BPrompt To Fix All With AI
Reviews (2): Last reviewed commit: "fix(handler): derive password error stri..." | Re-trigger Greptile