From c6bd833124c2283ff7d00d9efa6be807622ef676 Mon Sep 17 00:00:00 2001 From: Mathias Quintero Date: Tue, 25 Aug 2026 14:51:28 +0100 Subject: [PATCH] Improve Performance for HTTPField.Name Initializers (#144) # Motivation Currently when initializing a Field Name, we create a canonical lowercased version of the field name. However, it is reasonable to expect that a significant amount of the time the users will insert a name string that is already lowercased, so turning it into lowercase creates an extra unnecessary allocation # Changes This changes the validation step for the name to compute in a single pass whether the name is valid and if it's already in the canonical lowercased format. If it's already lowercased, then we can skip the extra allocation and just reuse the same string. if it's valid but not lowercased we can default to the previous logic. For ultimate performance this iterates over Spans whenever we use Swift 6.4. For other Swift versions, we default to iterating over the UTF8View instead, which is slightly slower, but keeps us backwards compatible. # Result More performance --- ...d.Name.init-alreadyLowercaseNames.p90.json | 2 +- ...d.Name.init-alreadyLowercaseNames.p90.json | 2 +- ...d.Name.init-alreadyLowercaseNames.p90.json | 2 +- ...d.Name.init-alreadyLowercaseNames.p90.json | 2 +- ...d.Name.init-alreadyLowercaseNames.p90.json | 2 +- Sources/HTTPTypes/HTTPField.swift | 131 ++++++++++++++++-- Sources/HTTPTypes/HTTPFieldName.swift | 21 +-- 7 files changed, 129 insertions(+), 33 deletions(-) diff --git a/Benchmarks/Thresholds/6.1/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json b/Benchmarks/Thresholds/6.1/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json index 7f38778..1d75e13 100644 --- a/Benchmarks/Thresholds/6.1/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json +++ b/Benchmarks/Thresholds/6.1/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 1016 + "mallocCountTotal" : 16 } \ No newline at end of file diff --git a/Benchmarks/Thresholds/6.2/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json b/Benchmarks/Thresholds/6.2/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json index 7f38778..1d75e13 100644 --- a/Benchmarks/Thresholds/6.2/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json +++ b/Benchmarks/Thresholds/6.2/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 1016 + "mallocCountTotal" : 16 } \ No newline at end of file diff --git a/Benchmarks/Thresholds/6.3/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json b/Benchmarks/Thresholds/6.3/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json index 63ed756..ff64d7f 100644 --- a/Benchmarks/Thresholds/6.3/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json +++ b/Benchmarks/Thresholds/6.3/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 1018 + "mallocCountTotal" : 18 } \ No newline at end of file diff --git a/Benchmarks/Thresholds/nightly-main/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json b/Benchmarks/Thresholds/nightly-main/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json index 63ed756..ff64d7f 100644 --- a/Benchmarks/Thresholds/nightly-main/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json +++ b/Benchmarks/Thresholds/nightly-main/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 1018 + "mallocCountTotal" : 18 } \ No newline at end of file diff --git a/Benchmarks/Thresholds/nightly-next/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json b/Benchmarks/Thresholds/nightly-next/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json index 63ed756..ff64d7f 100644 --- a/Benchmarks/Thresholds/nightly-next/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json +++ b/Benchmarks/Thresholds/nightly-next/Benchmarks.HTTPField.Name.init-alreadyLowercaseNames.p90.json @@ -1,3 +1,3 @@ { - "mallocCountTotal" : 1018 + "mallocCountTotal" : 18 } \ No newline at end of file diff --git a/Sources/HTTPTypes/HTTPField.swift b/Sources/HTTPTypes/HTTPField.swift index 4e7b925..3057e27 100644 --- a/Sources/HTTPTypes/HTTPField.swift +++ b/Sources/HTTPTypes/HTTPField.swift @@ -272,17 +272,126 @@ extension HTTPField: Codable { @available(HTTPTypes 1.0, *) extension HTTPField { - static func isValidToken(_ token: some StringProtocol) -> Bool { - !token.isEmpty - && token.utf8.allSatisfy { - switch $0 { - case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E: - return true - case 0x30...0x39, 0x41...0x5A, 0x61...0x7A: // DIGHT, ALPHA - return true - default: - return false - } + private enum TokenValidity { + case invalid + case valid + case canonical + + var isValid: Bool { + switch self { + case .valid, .canonical: + return true + case .invalid: + return false } + } + } + + private static var digits: ClosedRange { + UInt8(ascii: "0")...UInt8(ascii: "9") + } + + private static var lowerCaseLetters: ClosedRange { + UInt8(ascii: "a")...UInt8(ascii: "z") + } + + private static var upperCaseLetters: ClosedRange { + UInt8(ascii: "A")...UInt8(ascii: "Z") + } + + static func validatedCanonicalName(_ name: String) -> String? { + switch Self.tokenValidity(name) { + case .canonical: + return name + case .valid: + return name.lowercased() + case .invalid: + return nil + } + } + + static func isValidToken(_ token: String) -> Bool { + Self.tokenValidity(token).isValid + } + + static func isValidToken(_ token: Substring) -> Bool { + Self.tokenValidity(token).isValid + } + + #if compiler(>=6.3) && !(os(watchOS) && _pointerBitWidth(_32)) + private static func tokenValidity(_ token: String) -> TokenValidity { + #if canImport(Darwin) + if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) { + return Self.tokenValidity(token.utf8.span) + } + return Self.tokenValidity(token.utf8) + #else + return Self.tokenValidity(token.utf8.span) + #endif + } + + private static func tokenValidity(_ token: Substring) -> TokenValidity { + #if canImport(Darwin) + if #available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) { + return Self.tokenValidity(token.utf8.span) + } + return Self.tokenValidity(token.utf8) + #else + return Self.tokenValidity(token.utf8.span) + #endif + } + + @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) + private static func tokenValidity(_ buffer: borrowing Span) -> TokenValidity { + // Checks validity of token based on [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens) + if buffer.isEmpty { + return .invalid + } + + var validity: TokenValidity = .canonical + for index in buffer.indices { + switch buffer[index] { + // Symbols like "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E: + continue + case Self.digits, Self.lowerCaseLetters: + continue + case Self.upperCaseLetters: + validity = .valid + default: + return .invalid + } + } + + return validity + } + #else + private static func tokenValidity(_ token: some StringProtocol) -> TokenValidity { + Self.tokenValidity(token.utf8) + } + #endif + + private static func tokenValidity(_ bytes: some Collection) -> TokenValidity { + // Checks validity of token based on [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens) + if bytes.isEmpty { + return .invalid + } + + var validity: TokenValidity = .canonical + for byte in bytes { + switch byte { + // Symbols like "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E: + continue + case Self.digits, Self.lowerCaseLetters: + continue + case Self.upperCaseLetters: + validity = .valid + default: + return .invalid + } + } + + return validity } } diff --git a/Sources/HTTPTypes/HTTPFieldName.swift b/Sources/HTTPTypes/HTTPFieldName.swift index 209b161..18ccf4e 100644 --- a/Sources/HTTPTypes/HTTPFieldName.swift +++ b/Sources/HTTPTypes/HTTPFieldName.swift @@ -42,11 +42,12 @@ extension HTTPField { /// - Parameter name: The name of the HTTP field. It can be accessed from the `rawName` /// property. public init?(_ name: String) { - guard HTTPField.isValidToken(name) else { + guard let canonicalName = HTTPField.validatedCanonicalName(name) else { return nil } + self.rawName = name - self.canonicalName = name.lowercased() + self.canonicalName = canonicalName } /// Create an HTTP field name from a string produced by HPACK or QPACK decoders used in @@ -59,27 +60,13 @@ extension HTTPField { /// be lowercased. @available(HTTPTypes 1.2, *) public init?(parsed name: String) { - guard !name.isEmpty else { - return nil - } let token: Substring if name.utf8.first == UInt8(ascii: ":") { token = name.dropFirst() } else { token = Substring(name) } - guard - token.utf8.allSatisfy({ - switch $0 { - case 0x21, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2A, 0x2B, 0x2D, 0x2E, 0x5E, 0x5F, 0x60, 0x7C, 0x7E: - return true - case 0x30...0x39, 0x61...0x7A: // DIGHT, ALPHA - return true - default: - return false - } - }) - else { + guard HTTPField.isValidToken(token) else { return nil } self.rawName = name