본문 바로가기
iOS/Study

[Study/iOS] Method Dispatch

by Callie_ 2023. 12. 2.

 

 

 

SweepSwift iOS 면접 질문에 대한 답을 작성한 김에 iOS 개발자라면 앱의 기능향상 면에서 꼭 고려해봐야한다는 Method Dispatch에 대해 정리해보기로 했다.

 

 

 

 

✔︎ Method Dispatch

Method dispatching is the process of finding the address of instructions to be executed by the CPU when a particular method is called.

 

어떤 인스턴스의 호출구문에서 프로그램이 어떤 메서드를 실행할지 선택하는 것을 메소드 디스패치라고 한다.

어느 시점(컴파일타임 vs 런타임)에 어떤 method를 사용할지를 결정하느냐에 따라서 Static DispatchDynamic Dispatch로 나뉜다.

 

사실 종류는 Inline Dispatch, Virtual Dispatch를 포함하여 4가지인데, 주로 고려해야하는 건 Dynamic Dispatch와 Static Dispatch다. 

 

 

 

 

✔︎ Dynamic Dispatch

  • 런타임에 결정
  • 참조타입 (Class)
  • 클래스의 경우 컴파일 타임에서 참조될 요소의 위치가 명확하게 결정되지 않기 때문에 런타임에서 실제 참조될 요소가 결정된다. 이 과정으로 인해 오버헤드가 발생할 수 있다.
  • 어떤 서브클래스가 들어와도 실제에 맞는 요소를 참조하기 때문에 다형성 활용에 유리
  • final 키워드를 통해 참조타입인 경우 특정 인스턴스를 재상속을 방지하여 정적 디스패치로 만들어 성능을 향상 시킬 수 있다.

 

 

 

 

✔︎  Static Dispatch

  • 컴파일 타임에 결정
  •  값타입과 참조타입(class, struct 모두)에서 모두 사용이 가능하다.
  •  protocol과 extension은 Static Dispatch에서 동작한다.
  • Static Dispatch가 Dispatch 종류 중 속도가 가장 빠른데,  그 이유가 static dispatch prohibits methods from being overridden, resulting in only one implementation of each method. 즉, 재상속을 방지해서이다.

 

 

 

 

 

 

 

📌  References

 

https://medium.com/@ilichev/method-dispatch-in-swift-da0d3993fc76

 

Method Dispatch in Swift

Introduction

medium.com

 

'iOS > Study' 카테고리의 다른 글

[iOS] 이미지 캐시  (1) 2024.04.03
[iOS] Keychain vs UserDefaults  (0) 2023.12.17
[iOS] 앱의 생명주기  (0) 2023.11.27
[Study/iOS] unowned vs weak  (2) 2023.11.14
[Swift] Enum with Reusable VC  (0) 2023.10.10