Skip to content

perf(aws_role): compile ARN regexp once at package level#1525

Open
b-wulan wants to merge 1 commit into
Versent:masterfrom
b-wulan:opt/2026-05-26-cache-aws-role-regexp-v2
Open

perf(aws_role): compile ARN regexp once at package level#1525
b-wulan wants to merge 1 commit into
Versent:masterfrom
b-wulan:opt/2026-05-26-cache-aws-role-regexp-v2

Conversation

@b-wulan

@b-wulan b-wulan commented May 26, 2026

Copy link
Copy Markdown

File changed:

aws_role.go

Optimization:

Moved regexp.Compile(...) from inside parseRole() (called once per role) to a package-level regexp.MustCompile variable awsRoleRe. The pattern is identical — only the compilation site moved.

+var awsRoleRe = regexp.MustCompile(`arn:([^:\n]*):([^:\n]*):([^:\n]*):([^:\n]*):(([^:/\n]*)[:/])?([^:,\n]*)`)

 func parseRole(role string) (*AWSRole, error) {
-    r, _ := regexp.Compile("arn:([^:\n]*):([^:\n]*):([^:\n]*):([^:\n]*):(([^:/\n]*)[:/])?([^:,\n]*)")
-    tokens := r.FindAllString(role, -1)
+    tokens := awsRoleRe.FindAllString(role, -1)

Why it improves the project:

parseRole is called once per AWS role in the SAML response — a typical multi-account SSO session may return dozens of roles. Compiling a regexp involves NFA/DFA construction, which allocates and is CPU-intensive. Doing this once at startup instead of on every call eliminates that overhead entirely.

The original code also silently discarded the regexp.Compile error (r, _ := ...). If the pattern were somehow invalid, r would be nil and r.FindAllString would panic mid-execution. regexp.MustCompile at package level converts any such failure into a startup-time panic, which is the correct Go convention for static patterns.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant