# Converting Class objects into Data to serialise as .dat file

**URL:** <https://forums.swift.org/t/converting-class-objects-into-data-to-serialise-as-dat-file/62127>\
**Category:** Using Swift\
**Tags:** data, serialization\
**Created:** [December 19, 2022, 8:17am UTC](https://forums.swift.org/t/converting-class-objects-into-data-to-serialise-as-dat-file/62127 "2022-12-19T08:17:59Z")\
**Posts on this page:** 1\
**Showing post:** 27

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [February 16, 2023, 4:36pm UTC](https://forums.swift.org/t/converting-class-objects-into-data-to-serialise-as-dat-file/62127/27 "2023-02-16T16:36:42Z")

</div>

> [@tera](#):
>
> I concur with that observation. In some of my tests Codable based serialisation was the slowest, Mirror based serialisation was about an order of magnitude quicker than Codable and manual serialisation was an order of magnitude quicker than Mirror, making it two orders of magnitude faster than Codable.

I debugged my test and found one of the major contributor to slowness in the Codable based serialiser:

```swift
class MyEncoder: Encoder {
    ...
    func encode(_ value: Float) {
        ...
    }
    func encode<T: Encodable>(_ val: T) {
        try! val.encode(to: self)
    }
    ....

    private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
        var myEncoder: MyEncoder
        
        func encode<T: Encodable>(_ value: T, forKey key: Key) {
            myEncoder.encode(value)
        }
        ...
    }
    ...
}

```

Stepping through the line "myEncoder.encode(value)" where the value passed was Float, the resulting "encode" method being called was not the specialised "encode(\_ value: Float)" but generic "encode\<T: Encodable\>(\_ val: T)" (why it is this way is discussed [here](https://forums.swift.org/t/nested-generic-trouble/63152/3)). I put the workaround and interestingly that one change sped the serialised 10 times, so now my codable based serialised is just 10x slower than the manual serialiser.

---

_[View the full topic](https://forums.swift.org/t/converting-class-objects-into-data-to-serialise-as-dat-file/62127)._
