Skip to content

Commit

Permalink
Improve HTTPHeaders description performance
Browse files Browse the repository at this point in the history
Motivation:

As outlined in this [issue](apple#2930) by @weissi, the current performance of calling `description`
on `HTTPHeaders` is undermined by the dynamism of Array.

Modifications:

The proposed solution replaces the implementation of `description` to iterate over the items and print them out manually. This provides a faster solution since we bypass the cost of calling into `description` of an Array.

Result:

A more performant implementation of `HTTPHeaders` description.
  • Loading branch information
supersonicbyte committed Jan 15, 2025
1 parent a026de3 commit a860392
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Sources/NIOHTTP1/HTTPTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,10 @@ public struct HTTPHeaders: CustomStringConvertible, ExpressibleByDictionaryLiter
internal var keepAliveState: KeepAliveState = .unknown

public var description: String {
self.headers.description
self.headers.lazy.map {
"\($0.0): \($0.1)"
}
.joined(separator: "; ")
}

internal var names: [String] {
Expand Down
22 changes: 22 additions & 0 deletions Tests/NIOHTTP1Tests/HTTPHeadersTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -400,4 +400,26 @@ class HTTPHeadersTest: XCTestCase {
headers.reserveCapacity(4)
XCTAssertEqual(headers.capacity, 4)
}

func testHTTPHeadersDescription() {
let originalHeaders = [
("User-Agent", "1"),
("host", "2"),
("X-SOMETHING", "3"),
("SET-COOKIE", "foo=bar"),
("Set-Cookie", "buz=cux"),
]

let headers = HTTPHeaders(originalHeaders)

let expectedOutput = """
User-Agent: 1; \
host: 2; \
X-SOMETHING: 3; \
SET-COOKIE: foo=bar; \
Set-Cookie: buz=cux
"""

XCTAssertEqual(expectedOutput, headers.description)
}
}

0 comments on commit a860392

Please sign in to comment.