A Fast Timestamp Parser in Swift
It’s well known that
DateFormatter
, the main timestamp formatter and parser Apple ships in Foundation, is not particularly fast. It’s flexible and it’s correct, but it takes its time. The newerISO8601DateFormatter
has similar performance.[…]
Swift’s C bridging is first-class;
struct tm
andtimegm(3)
are right there. After changing the code to use those, the wholeString
toDate
conversion runs completely without heap allocations and it’s around 6–7 times faster than when doing the detour viaDateComponents
.The final result, according to Benchmark, is maybe around 15x the speed of the Foundation parsers. I’m pretty happy with it. It’s available as a Swift package, there’s documentation, and if you need something different or don’t feel like using a package, all the parsing code is in just one file you can copy over to your project.
You can set set it as a JSONDecoder.DateDecodingStrategy
.
Previously: