Skip to content

Commit a860392

Browse files
Improve HTTPHeaders description performance
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.
1 parent a026de3 commit a860392

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

Sources/NIOHTTP1/HTTPTypes.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,10 @@ public struct HTTPHeaders: CustomStringConvertible, ExpressibleByDictionaryLiter
313313
internal var keepAliveState: KeepAliveState = .unknown
314314

315315
public var description: String {
316-
self.headers.description
316+
self.headers.lazy.map {
317+
"\($0.0): \($0.1)"
318+
}
319+
.joined(separator: "; ")
317320
}
318321

319322
internal var names: [String] {

Tests/NIOHTTP1Tests/HTTPHeadersTest.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,4 +400,26 @@ class HTTPHeadersTest: XCTestCase {
400400
headers.reserveCapacity(4)
401401
XCTAssertEqual(headers.capacity, 4)
402402
}
403+
404+
func testHTTPHeadersDescription() {
405+
let originalHeaders = [
406+
("User-Agent", "1"),
407+
("host", "2"),
408+
("X-SOMETHING", "3"),
409+
("SET-COOKIE", "foo=bar"),
410+
("Set-Cookie", "buz=cux"),
411+
]
412+
413+
let headers = HTTPHeaders(originalHeaders)
414+
415+
let expectedOutput = """
416+
User-Agent: 1; \
417+
host: 2; \
418+
X-SOMETHING: 3; \
419+
SET-COOKIE: foo=bar; \
420+
Set-Cookie: buz=cux
421+
"""
422+
423+
XCTAssertEqual(expectedOutput, headers.description)
424+
}
403425
}

0 commit comments

Comments
 (0)