It will take about 3 minutes to finish reading this article.
As we all know that, Since struct instances are allocated on stack, and class instances are allocated on heap, structs can sometimes be drastically faster. So there is an example here can prove that.
Consider the following example, which demonstrates 2 strategies of wrapping Int data type using struct and class. Using 10 repeated values are to better reflect real world, where you have multiple fields.
func+ (x: IntStruct, y: IntStruct) -> IntStruct { returnIntStruct(x.value + y.value) } // 10 fields classInt10Class { let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int init(_val: Int) { self.value1 = val self.value2 = val self.value3 = val self.value4 = val self.value5 = val self.value6 = val self.value7 = val self.value8 = val self.value9 = val self.value10 = val } }
structInt10Struct { let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int init(_val: Int) { self.value1 = val self.value2 = val self.value3 = val self.value4 = val self.value5 = val self.value6 = val self.value7 = val self.value8 = val self.value9 = val self.value10 = val } }
classTests { staticfuncrunTests() { print("Running tests") measure("class (1 field)") { var x =IntClass(0) for_in1...10000000 { x = x +IntClass(1) } } measure("struct (1 field)") { var x =IntStruct(0) for_in1...10000000 { x = x +IntStruct(1) } } measure("class (10 fields)") { var x =Int10Class(0) for_in1...10000000 { x = x +Int10Class(1) } } measure("struct (10 fields)") { var x =Int10Struct(0) for_in1...10000000 { x = x +Int10Struct(1) } } } staticprivatefuncmeasure(_name: String, block: @escaping () -> ()) { print() print("\(name)") let t0 =CACurrentMediaTime() block() let dt =CACurrentMediaTime() - t0 print("\(dt)") } }
We can find somewhere in our project and just run the following code:
1
Tests.runTests()
One of my running results is as follows:
1 2 3 4 5 6 7 8 9 10 11
class (1 field) 6.262335019011516
struct (1 field) 3.954203129003872
class (10 fields) 6.161917756006005
struct (10 fields) 4.097320644999854
We can find that ‘struct’ type is more faster than ‘class’ type.