Hacker News new | ask | show | jobs
by jamamp 1026 days ago
Swift's `Codable`[0] system seems very similar to serde in this regard. Structs that you define can be marked with the Codable protocol, and the Swift compiler automatically generates code during compilation that encodes from and decodes to the structs properties, with the option for you to customize it using CodingKeys for different properties names or completely custom coding behavior.

It seems built-in to Swift, as opposed to a dynamically executed crate like with serde. I wonder how it's implemented in Swift and if it leads to any significant slowdowns.

[0] https://developer.apple.com/documentation/foundation/archive...

2 comments

Codable (along with other derived conformances like Equatable, Hashable, and RawRepresentable) is indeed built in to the compiler[0], but unlike Serde, it operates during type-checking on a fully-constructed AST (with access to type information), manipulating the AST to insert code. Because it operates at a later stage of compilation and at a much higher level (with access to type information), the work necessary is significantly less. (It's difficult to compare Serde and Codable in a way that isn't apples-and-oranges, but at the very least, Codable makes use of information that the compiler has done, and has already needed to do anyway; there's very little manipulation it needs to do to achieve its aims.)

With ongoing work for Swift macros, it may eventually be possible to rip this code out of the compiler and rewrite it as a macro, though it would need to be a semantic macro[1] rather a syntactic one, which isn't currently possible in Swift[2].

[0] https://github.com/apple/swift/blob/main/lib/Sema/DerivedCon... [1] https://gist.github.com/DougGregor/4f3ba5f4eadac474ae62eae83... [2] https://forums.swift.org/t/why-arent-macros-given-type-infor...

Last I checked[1], Swift JSON performance was terrible, well over an order of magnitude slower than serde. It's possible it's been improved since then but if so I didn't find any announcement.

[1]: https://github.com/xi-editor/xi-mac/issues/102

The problem wasn't Swift Codable, the problem was Apple's implementation of JSONEncoder / Decoder on top of Obj-C runtime, which created unnecessary round trips.

It was only fully addressed in Swift 5.9.

Both are problems, and it's far from fully addressed in Swift 5.9. The new Swift implementation of JSONEncoding is "only" 2-5x faster than the old one, so while it's a big improvement it's still very slow. Codable itself is also very performance-hostile, and a no-op encoder which fully walks the input but doesn't produce any output will be slower than serde producing json.
Can you get into more details on why do you think Codable is performance hostile?