Friday, July 21, 2023

A Fast Timestamp Parser in Swift

Juri Pakaste (Mastodon):

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 newer ISO8601DateFormatter has similar performance.

[…]

Swift’s C bridging is first-class; struct tm and timegm(3) are right there. After changing the code to use those, the whole String to Date conversion runs completely without heap allocations and it’s around 6–7 times faster than when doing the detour via DateComponents.

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:

Comments RSS · Twitter · Mastodon

Leave a Comment