WWDC2016 Understanding Swift Performance

김민종·2023년 3월 4일
0

WWDC

목록 보기
3/4

Dimensions of Performance

Allocation,Reference Counting, Method Dispatch


These three steps are required considerations while progrmming in swift
For better performance of your code!

Allocation

Swift automatically allocate and deallocates memory.

Stack
First stack is simple data structure. Just push and pop the data by using stack pointer.
Stack allocation is really fast

Heap
Heap is more dynamic but less efficient than stack.
Multiple thread could be allocated at heap, So heap needs to lock or use synchroization mechanism by keep integrity. And it's pretty large cost

Value and Reference Semantics

Struct, enum, tuple are value semantics.
It copies when allocate instance to other instance.
Copied instance are seperated from original instance so it doesn't affect original instance.

class is reference semantics. So reference sematics allocate reference address at stack and allocate actual data at heap.

When initiallize class instance and copying it point1, point2 are all pointing reference and address at stack.
So when the value changes it seems like instance data is changing together.
This could end to unintent change of data

So ther class costs a lot more than struct.

Reference Counting

Allocating to heap it self means using reference counting
When instance is made Point class data is allocated at heap.
and at stack the reference will be saved and increases reference counting.
And copying point1 instance to another instance, reference count increases by 2.
When modifying point2, two instances(point1,point2) which are heap instance property seems like it changing it value.
When decresing reference count atomatically to 0, swift it self defines that is safe to deallocate the memory and returns memory block.

Method Dispatch

method dispatch is procees of determining which method to use by program. At the point which method will be used it splits with static method dispatch and dynamic method dispatch.

Static Method Dispatch

Compiler knows where the code exists so the code executes at compile time.

Dynamic Method Dispatch

Finding method and executes at runtime

Summary

Allocation, reference couting, method dispatch are affects swift performance.
So, when writing code or reviewing code we should consider those three things.

Considering allocation, reference couting, method dispatch, can find why apple prefers struct rather than class. But, not always struct is better than class.

Referecnce: WWDC 2016 Understanding Swift Performormance

profile
신입 ios개발자입니다!

0개의 댓글