Junior — Middle
Which approach — structure or class — has better performance?
sobes.tech AI
Answer from AI
In iOS (Swift), structures and classes have different characteristics that affect performance:
- Structures (struct) are value types that are copied when passed. They are generally faster to create and deallocate because they do not require memory management through ARC (Automatic Reference Counting).
- Classes (class) are reference types managed through ARC. Creating and destroying class objects requires additional work for reference counting.
Therefore, if an object is small and does not require inheritance, structures usually offer better performance due to the absence of overhead for memory management.
Example:
struct Point {
var x: Int
var y: Int
}
class Node {
var value: Int
init(value: Int) {
self.value = value
}
}
Use structures for lightweight, immutable data, and classes when inheritance or reference-based state management is needed.