Swift — difference between struct and class

Time:2022-5-11
Classes and structures in swift are very similar. They both have object-oriented features such as defining and using attributes, methods, subscripts and constructors. However, structures do not have inheritance, nor do they have the ability to force type conversion at runtime, use destructors and reference counting!

In swift, struct is the value type and class is the reference type. Variables of value type directly contain their data. Variables of reference type store data references to them, so the latter is called object. Therefore, operating on one variable may affect all referenced objects of another variable. Each value type has its own copy of data, so an operation on one variable cannot affect another variable.

1. Definition and instantiation comparison of class and structure

//Define class
Class name{
  //Defines the members of a class
}
//Create a class named classcoder
class ClassCoder {
 var name = "IAMXH"
 var age = 0
}

//Define structure
Struct structure name{
  //Defines the members of the structure
}
//Create a struct named structcoder
struct StructCoder {
 var name = "IAMXH"
 var age = 0

}
//Class instantiation
let classCoder = ClassCoder()
//Class cannot use classcoder directly (Name: "XH", age: 25). You must create your own constructor
classCoder.name = "XH"
classCoder.age = 25
 
//Structure instantiation
var structCoder = StructCoder(name:"XH",age:25)
//Another instantiation method
var structCoder = StructCoder()
structCoder.name = "XH"
structCoder.age = 25

Class cannot automatically put property in the parameters of the constructor when instantiating. You must create your own constructor.

2. Mutating keyword

//Add a method: modifycodername (newname:) without modifying class and struct

//Class
extension ClassCoder {
    func modifyCoderName(newName:String) {
        
        self.name = newName
    }
}

//Structure
extension StructCoder{
    mutating func modifyCoderName(newName:String) {
        self.name = newName
    }
}

When struct needs to change property in func, it needs to add the mutating keyword, but class doesn’t.

3. Class can inherit, but struct cannot.

As the title, do not explain

4. Memory allocation: struct memory is allocated to the stack and class memory is allocated to the heap

The storage structure of stack memory is relatively simple, which can be understood as pushing to the pop at the bottom of the stack. What we need to do is to allocate and destroy memory by moving the stack needle.

Heap memory has a more responsible storage structure than stack. Its allocation method can be understood as finding a free memory block of appropriate size in the heap to allocate memory, reinserting the memory block into the heap and destroying memory. Of course, these are only one aspect of the large consumption of heap memory compared with stack memory. More importantly, heap memory supports multi-threaded operation, and the response should ensure thread safety through synchronization and other methods.

struct Point {
   var x, y: Double
   func draw() { ... }
}
let point1 = Point(x: 0, y: 0)
var point2 = point1
point2.x = 5

First, before the code is executed, the compiler will allocate a block of memory with the size of 4 words on the stack. The allocation process is to move the stack needle I mentioned above

Swift -- difference between struct and class

Figure I

Initializing point1 with (0,0) and assigning point1 to point2 can be understood as copying value to the allocated stack memory. Because struct is a value type, point1 and point2 are two independent instances

Swift -- difference between struct and class

Figure II

Modify point2 X does not affect point1

Swift -- difference between struct and class

Figure 3

Finally, use point1 and use point2 leave the scope, move the stack needle and destroy the stack memory

Next, let’s take a look at class


class Point {
   var x, y: Double
   func draw() { ... }
}
let point1 = Point(x: 0, y: 0)
let point2 = point1

First, before code execution, the compiler will allocate two word sized memory on the stack, but this time it is not used to store the property of point

Swift -- difference between struct and class

4

Code execution initializes point1 to find the memory block allocation of appropriate size on the heap

Swift -- difference between struct and class

5

Then copy the value to the heap memory storage, and store a pointer to the heap memory on the stack

Swift -- difference between struct and class

6

You can see that four word sized memory blocks are allocated on the heap, and the remaining two blue squares store pointers to the function tables related to the class life cycle
Let point2 = point1 executes the reference language, but a pointer to point1 heap memory is stored in the stack memory of point2

Swift -- difference between struct and class

7

Modify point2 X also affects point1

Swift -- difference between struct and class

8

Finally, use point1 and use point2 leave the scope, the heap memory is destroyed (find and reinsert the memory block into the stack memory), and the stack memory is destroyed (move the stack needle)
Of course, in the process of allocation in the stack, we also need to ensure thread safety (which is also a lot of overhead)

5. Reference count: structs are stack memory allocation and do not involve any reference count

6. Distribution method:

Static dispatch: the compiler says that the function address is directly encoded in the assembly. When calling, the compiler directly jumps to the implementation according to the address. The compiler can optimize inlining and so on. Struct is static dispatch.
Dynamic distribution: look up the function table at runtime, and then jump to the implementation. The reason why dynamic distribution is only one more table lookup link is not that it is slow. The real reason is that it prevents the compiler from inline and other optimization methods

Reference article:

Swift — difference between struct and class
Struct and class in swift
Understand the performance differences between struct and class in swift under different situations