Skip to content

Conversation

@florianl
Copy link
Contributor

Description

Initializing a package global map and compiling regexes increases the init functions and adds up to the start time of executables.

This change implements two approaches:

  • compile the regex on its first use
  • rewrite the map to a switch case statement

How Has This Been Tested?

Minimal example:

package main

import "github.com/hashicorp/go-version"

func main() {
	v, err := version.NewSemver("1.2.3")
	if err != nil {
		panic(err)
	}
	println(v.String())
}

On Go 1.25.4 linux/amd64 the above code compiles to ~2728103 bytes and GODEBUG=inittrace=1 shows the following:

init github.com/hashicorp/go-version @0.90 ms, 0.37 ms clock, 80992 bytes, 504 allocs

With this change applied on the same system, the above code compiles to ~2703283 bytes (reduction of ~24820 bytes) and GODEBUG=inittrace=1 does not list any init entry for github.com/hashicorp/go-version anymore.

Related Issue

Initializing a package global map and compiling regexes increases the init
functions and adds up to the start time of executables.

This change implements two approaches:

- compile the regex on its first use
- rewrite the map to a switch case statement

Minimal example:
```
package main

import "github.com/hashicorp/go-version"

func main() {
	v, err := version.NewSemver("1.2.3")
	if err != nil {
		panic(err)
	}
	println(v.String())
}
```

On Go 1.25.4 linux/amd64 the above code compiles to ~2728103 bytes and
GODEBUG=inittrace=1 shows the following:

init github.com/hashicorp/go-version @0.90 ms, 0.37 ms clock, 80992 bytes, 504 allocs

With this change applied on the same system, the above code compiles to ~2703283
bytes (reduction of ~24820 bytes) and GODEBUG=inittrace=1 does not list any init entry for
github.com/hashicorp/go-version anymore.

Signed-off-by: Florian Lehner <dev@der-flo.net>
@florianl florianl requested a review from a team as a code owner November 19, 2025 20:44
@hashicorp-cla-app
Copy link

hashicorp-cla-app bot commented Nov 19, 2025

CLA assistant check
All committers have signed the CLA.

Copy link

@CreatorHead CreatorHead left a comment

Choose a reason for hiding this comment

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

Thanks for the refactor, removing the init() and moving to sync.Once lazy compilation makes the package a lot cleaner and eliminates side effects at import time.

LGTM

@ssagarverma ssagarverma merged commit 505335e into hashicorp:main Nov 21, 2025
1 check passed
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.

3 participants