Files
Mathias QuinteroandFabian Fett f41c097554 Improve Performance of HTTPField.value (#146)
### Motivation

When instantiating new HTTPFields, the values need to be validated,
legalized and turned into the internal representation.
We use this representation to expose a string in `HTTPField.value` as
well as to iterate over raw bytes using
`HTTPField.withUnsafeBytesOfValue`.

Currently the internal representation is to use a ISO Latin 1 String to
store the bytes only once. This however means that we need to transcode
back and forth for non ascii values, which causes a lot of extra
computations and allocations.

### Modifications

1. Moved logic to a standalone structure for `HTTPField.Value` rather
than `ISOLatin1String`
2. Added Unit Tests and Benchmarks
3. Swapped internal storage of values to be an enum of either a string
or a value
4. Whenever the bytes stored are valid utf8, we will not always store
the value as a raw string. This means that we need the least amount of
allocations and transcoding when operating with the value through our
public API
5. We only store a raw array of bytes whenever the bytes are not valid
utf8. This speeds up `withUnsafeBytesOfValue` massively and
`HTTPField.value` a little bit
6. During legalization, store the modified bytes in a temporary buffer
instead of using lazy collections to avoid allocating an array and speed
up utf8 validation
7. Use spans whenever possible to speed up access to bytes without
boundary checks

### Result

These are the changes on the benchmarks added in this PR

```
HTTPField-asciiBytesValueRoundTrip
Instructions: 28K -> 6847 (-75%)
Malloc: 1 -> 1

HTTPField-asciiValueRoundTrip
Instructions: 7367 -> 3081 (-58%)
Malloc: 0 -> 0

HTTPField-invalidAsciiBytesValueRoundTrip
Instructions: 133K -> 7255 (-94%)
Malloc: 6 -> 1 (-83%)

HTTPField-invalidAsciiBytesValueRoundTripAsLenientValue
Instructions: 62K -> 6623 (-89%)
Malloc: 3 -> 1 (-66%)

HTTPField-invalidAsciiValueRoundTrip
Instructions: 93K -> 6959 (-92%)
Malloc: 5 -> 1 (-80%)

HTTPField-invalidNonASCIIValueRoundTrip
Instructions: 393K -> 8735 (-97%)
Malloc: 11 -> 1 (-91%)

HTTPField-nonASCIIValueRoundTrip
Instructions: 131K -> 3219 (-97%)
Malloc: 4 -> 0 (-100%)
```

---------

Co-authored-by: Fabian Fett <fabianfett@apple.com>
2026-08-31 11:30:56 +02:00

190 lines
6.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
@_spi(HTTPTypesBenchmarking) import HTTPTypes
import Testing
extension HTTPField.Name {
fileprivate static var foo: HTTPField.Name { .init(parsed: "foo")! }
}
@Suite struct HTTPFieldValueTests {
@Test func empty() {
let field = HTTPField(name: .foo, value: "")
#expect(field.value == "")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 0)
}
}
@Test func pureAscii() {
let field = HTTPField(name: .foo, value: "bar")
#expect(field.value == "bar")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 3)
#expect(String(decoding: buffer, as: UTF8.self) == "bar")
}
}
@Test func pureAsciiAsBytes() {
let value = "bar"
let field = HTTPField(name: .foo, value: value.utf8)
#expect(field.value == "bar")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 3)
#expect(String(decoding: buffer, as: UTF8.self) == "bar")
}
}
@Test func pureAsciiWithLeadingAndTrailingSpacesAndTabs() {
let field = HTTPField(name: .foo, value: " \t \t bar and baz \t \t ")
#expect(field.value == "bar and baz")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 11)
#expect(String(decoding: buffer, as: UTF8.self) == "bar and baz")
}
}
@Test func pureAsciiLenient() {
let value = "bar"
let field = HTTPField(name: .foo, lenientValue: value.utf8)
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 3)
#expect(String(decoding: buffer, as: UTF8.self) == "bar")
}
}
@Test func emoji() {
let field = HTTPField(name: .foo, value: "👍")
#expect(field.value == "👍")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 4)
#expect(String(decoding: buffer, as: UTF8.self) == "👍")
}
}
@Test func zeroWidthJoiner() {
let field = HTTPField(name: .foo, value: "🏳️‍🌈")
#expect(field.value == "🏳️‍🌈")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 14)
#expect(String(decoding: buffer, as: UTF8.self) == "🏳️‍🌈")
}
}
@Test func asciiWithControlBytesLegalized() {
let bytes: [UInt8] = [0x00, 0x62, 0x61, 0x00, 0x72, 0x00]
let field = HTTPField(name: .foo, value: bytes)
#expect(field.value == "ba r")
field.withUnsafeBytesOfValue { buffer in
#expect(Array(buffer) == [0x62, 0x61, 0x20, 0x72])
}
}
@Test func asciiWithControlBytesLenient() {
let bytes: [UInt8] = [0x00, 0x62, 0x61, 0x00, 0x72, 0x00]
let field = HTTPField(name: .foo, lenientValue: bytes)
#expect(field.value == " ba r ")
field.withUnsafeBytesOfValue { buffer in
#expect(Array(buffer) == [0x20, 0x62, 0x61, 0x20, 0x72, 0x20])
}
}
@Test func nonUTF8WithControlBytesLegalized() {
let bytes: [UInt8] = [
0xC0, // not valid UTF8. will be changed with replacement character in string representation
0x41, // simple ASCII
0xFF, // not valid UTF8. will be changed with replacement character in string representation
0x0A, // random control character which should be trimmed
]
let field = HTTPField(name: .foo, value: bytes)
#expect(field.value == "\u{FFFD}A\u{FFFD}")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 3)
#expect(buffer[0] == 0xC0)
#expect(buffer[1] == 0x41)
#expect(buffer[2] == 0xFF)
}
}
@Test func nonUTF8WithControlBytesLenient() {
let bytes: [UInt8] = [
0xC0, // not valid UTF8. will be changed with replacement character in string representation
0x41, // simple ASCII
0xFF, // not valid UTF8. will be changed with replacement character in string representation
0x0A, // random control character which should be swapped with a space
]
let field = HTTPField(name: .foo, lenientValue: bytes)
#expect(field.value == "\u{FFFD}A\u{FFFD} ")
field.withUnsafeBytesOfValue { buffer in
#expect(buffer.count == 4)
#expect(buffer[0] == 0xC0)
#expect(buffer[1] == 0x41)
#expect(buffer[2] == 0xFF)
#expect(buffer[3] == 0x20)
}
}
@Test func equalityOfString() {
let lhs = HTTPField(name: .foo, value: "bar")
let rhs = HTTPField(name: .foo, value: " bar ")
#expect(lhs == rhs)
}
@Test func inequalityOfStrings() {
let lhs = HTTPField(name: .foo, value: "bar")
let rhs = HTTPField(name: .foo, value: "baz")
#expect(lhs != rhs)
}
@Test func equalityOfBytes() {
let lhs = HTTPField(name: .foo, value: [0x00, 0x62, 0x61, 0x00, 0x72, 0xC0, 0x00])
let rhs = HTTPField(name: .foo, value: [0x00, 0x00, 0x62, 0x61, 0x00, 0x72, 0xC0, 0x00])
#expect(lhs == rhs)
}
@Test func inequalityOfBytes() {
let lhs = HTTPField(name: .foo, value: [0x00, 0x62, 0x61, 0x00, 0x72, 0xC0, 0x00])
let rhs = HTTPField(name: .foo, value: [0x00, 0x62, 0x61, 0x00, 0x7A, 0xC0, 0x00])
#expect(lhs != rhs)
}
@Test func inequalityOfStringAndBytes() {
let lhs = HTTPField(name: .foo, value: "bar")
// picked 0xC0 since it's guaranteed to not be utf8
let rhs = HTTPField(name: .foo, value: [0xC0, 0x62, 0x61, 0x00, 0x72, 0xC0])
#expect(lhs != rhs)
}
}