class is faster than struct

Generated on 8/23/2024

1 search

In Swift, the performance characteristics of classes and structs differ due to their storage and copying semantics. Classes use out-of-line storage and have reference semantics, meaning that copying a class value involves copying the ownership of the reference, which retains the object it refers to. This can be more efficient for larger types, as it avoids the cost of copying all stored properties.

On the other hand, structs use inline storage and have value semantics, meaning that copying a struct involves recursively copying all of its stored properties. This can be beneficial for small types, as it avoids heap allocation, but for larger types, the cost of copying can become a significant performance drag if many copies are made.

There is no definitive rule that classes are faster than structs or vice versa; it depends on the specific use case and the size of the data being handled. For more detailed insights, you can refer to the session Explore Swift performance at the "Value copying" chapter.