Swifty
Swifty

Reputation: 905

Are there any performance benefits of making a struct Encodable/Decodable instead of just Codable?

For an example struct Person that is to be serialized:

struct Person {
    let firstName: String
    let lastName: String
}

We could make it conform to the Encodable, Decodable or Codable protocols. I understand that our choice between Encodable and Decodable is contingent on the use case, (for example if we are hitting an API and do not need to decode a response containing the same type) but we could also make it conform to Codable if the struct is to be both used for encoding and decoding.

If we need the struct strictly for encoding or decoding, but not both, is it a bad idea from a performance perspective to just use a catch-all Codable instead of specifying Encodable/Decodable conformance?

An obvious disadvantage of using Codable instead of specifying Encodable/Decodable is that another programmer may misconstrue the struct as being used for encoding and decoding, when in reality only one of the two is happening. But what if I am strictly interested in performance?

Upvotes: 3

Views: 1025

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

There is no one dimension to "performance." It depends on what you mean. For example, adding Encodable conformance when it's not needed might increase the size of the binary, which could slow down launch time. Or it might be trivial, since binary size isn't very correlated to launch time (since the file is memory mapped). Or perhaps you mean compile-time performance, where clearly adding auto-generated conformances obviously require some additional complier work, and could in some cases increase the sea of types the type-checker needs to swim through, slowing things down a bit.

But for day-to-day work, it's hard to imagine a case where adding an unnecessary Encodable conformance would cause a table view to lag, if that's the kind of performance you mean. Your "another programmer may misconstrue" consideration is much more important.

Upvotes: 6

Related Questions