Skip to content
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

Speed up NewShaX #238

Merged
merged 1 commit into from
Jan 3, 2025
Merged

Speed up NewShaX #238

merged 1 commit into from
Jan 3, 2025

Conversation

qmuntal
Copy link
Collaborator

@qmuntal qmuntal commented Dec 20, 2024

In many places we create a hash object, e.g. by calling openssl.NewSHA256(), just to get the type of hash and map it to an OpenSSL hash identifier. Then the original hash is discarded. These pattern is common enough to worth optimizing.

This PR refactors the evpHash implementation so that the hash EVP_MD_CTX context is created and initialized lazily. These are the speed gains:

goos: windows
goarch: amd64
pkg: github.com/golang-fips/openssl/v2
cpu: Intel(R) Core(TM) i7-10850H CPU @ 2.70GHz
             │    old.txt     │               new.txt               │
             │     sec/op     │   sec/op     vs base                │
NewSHA256-12   1533.50n ± 27%   50.39n ± 8%  -96.71% (p=0.000 n=10)

             │  old.txt   │            new.txt             │
             │    B/op    │    B/op     vs base            │
NewSHA256-12   24.00 ± 0%   24.00 ± 0%  ~ (p=1.000 n=10) ¹
¹ all samples are equal

             │  old.txt   │            new.txt             │
             │ allocs/op  │ allocs/op   vs base            │
NewSHA256-12   1.000 ± 0%   1.000 ± 0%  ~ (p=1.000 n=10) ¹
¹ all samples are equal

@@ -360,6 +384,8 @@ func (d *evpHash) MarshalBinary() ([]byte, error) {
}

func (d *evpHash) AppendBinary(buf []byte) ([]byte, error) {
defer runtime.KeepAlive(d)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why is this KeepAlive necessary? (And why now?)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Not really necessary, as d is referenced after accessing the context. But I get nervous when I see a missing KeepAlive, as a refactor could break the code.

@qmuntal qmuntal merged commit 313c54f into v2 Jan 3, 2025
54 checks passed
@qmuntal qmuntal deleted the sppedhashinit branch January 3, 2025 14:56
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