apple / swift-nio

Event-driven network application framework for high performance protocol servers & clients, non-blocking.
https://swiftpackageindex.com/apple/swift-nio/documentation
Apache License 2.0
7.96k stars 651 forks source link

HTTPHeaders.description is unnecessarily slow #2930

Open weissi opened 1 week ago

weissi commented 1 week ago

Expected behavior

HTTPHeaders.description should be reasonably fast and shouldn't do any dynamic debugPrint(...)

Actual behavior

It's slow. Look at this image: about 15% of the overall runtime of a client hitting /dynamic/info is just spent doing header printing...

Screenshot 2024-10-16 at 12 35 25 pm

That's largely because of debugPrint etc.

Printing HTTP headers is somewhat common and shouldn't be unnecessarily fast. The representation could also be nicer.

supersonicbyte commented 5 days ago

I've looked at the code base a bit on HTTPHeaders and I see that the description just calls the description on the underlaying array of tuples: https://github.com/apple/swift-nio/blob/19da487ef29a8227745834e946f3203dd0c08cf2/Sources/NIOHTTP1/HTTPTypes.swift#L315

Maybe I am not looking at the proper type?

weissi commented 5 days ago

I've looked at the code base a bit on HTTPHeaders and I see that the description just calls the description on the underlaying array of tuples:

https://github.com/apple/swift-nio/blob/19da487ef29a8227745834e946f3203dd0c08cf2/Sources/NIOHTTP1/HTTPTypes.swift#L315

Maybe I am not looking at the proper type?

You are and that's the problem. Array uses a lot of unnecessary dynamism that we don't need here because it's just strings. So if you just did something like

return self.headers.lazy.map { header in
    "\(header.name): \(header.value)"
}.joined(separator: "; ")

or something similar, then it should be much faster.

We should discuss the format we want to return here. CC @Lukasa WDYT, format for HTTP headers for description/debugDescription?

Lukasa commented 5 days ago

We can do that, though the resolution of that format is poor: it'll mishandle some things that are otherwise fine. But for a first order approximation that output is ok.

supersonicbyte commented 5 days ago

@weissi thanks for the explanation, that's definitely todays TIL for me. I'm gonna be careful on calling description on array from now on!

If everyone agrees I can make a PR with the changes @weissi suggested.