apple / swift-crypto

Open-source implementation of a substantial portion of the API of Apple CryptoKit suitable for use on Linux platforms.
https://apple.github.io/swift-crypto
Apache License 2.0
1.43k stars 151 forks source link

Make HMAC authenticationCode and update inlinable #239

Closed baarde closed 1 week ago

baarde commented 3 weeks ago

Making the methods inlinable removes the cost of fetching the type metadata.

Checklist

Motivation:

As stated in #238, generally, users will only compute a few authentication codes and aren't really concerned by the performance. But sometimes, it may be necessary to compute a lot of authentication codes as fast as possible.

Making authenticationCode(for:using:) and update(data:) inlinable provides a significant performance gain when D is known at compile time without exposing much of the implementation.

Modifications:

Result:

On its own, this change makes computing HMAC authentication codes about 125% faster than before.

On my machine (MacBook Pro 14-inch 2021) HMAC-MD5: 49.6 seconds → 39.4 seconds HMAC-SHA1: 43.1 seconds → 33.7 seconds HMAC-SHA256: 44.6 seconds → 34.1 seconds HMAC-SHA384: 50.7 seconds → 41.3 seconds HMAC-SHA512: 50.3 seconds → 41.7 seconds
Test code ```swift import Crypto import Foundation func testHMAC(_ type: H.Type) { let start = Date() let iterations = 50_000_000 let key = SymmetricKey(data: Data()) var hmac = HMAC(key: key) let original = hmac var digest = hmac.finalize() for _ in 1 ..< iterations { hmac = original digest.withUnsafeBytes { bytes in hmac.update(data: bytes) } digest = hmac.finalize() } let duration = -start.timeIntervalSinceNow print("HMAC-\(H.self): \(String(format: "%.1f", duration)) seconds") } testHMAC(Crypto.Insecure.MD5.self) testHMAC(Crypto.Insecure.SHA1.self) testHMAC(Crypto.SHA256.self) testHMAC(Crypto.SHA384.self) testHMAC(Crypto.SHA512.self) ```
baarde commented 3 weeks ago

@Lukasa Thanks for your feedback. I'll use Feedback Assistant.

Would it be less ABI-impacting to make update(bufferPointer:) public?

Lukasa commented 2 weeks ago

Potentially, yes, it's worth suggesting in your Feedback Assistant report. Do you have the number handy?

baarde commented 1 week ago

@Lukasa I've submitted a feedback: FB14076813.

Lukasa commented 1 week ago

Thanks @baarde.