Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - Swift] 7. WWDC2024 정리 - (1) Explore Swift performance (Function call, Memory allocation) 본문

WWDC 정리/WWDC 2024 정리

[iOS - Swift] 7. WWDC2024 정리 - (1) Explore Swift performance (Function call, Memory allocation)

jake-kim 2024. 7. 1. 01:54

낮은 수준의 성능을 야기하는 요소 4가지

  • 1) Function call - 최적화 되지 않은 많은 함수 호출
  • 2) Memory allocation - 메모리 할당에 너무 많은 시간을 소비
  • 3) Memory layout - 데이터가 표현되는 방식 때문에 많은 시간이나 메모리 낭비
  • 4) Value copying - 불필요하게 값을 복사하고 파괴하는데 많은 시간을 소비

-> Swift perfomance는 대부분 위 4가지 비용 중 하나 이상에 영향을 미침

성능 1) Function call

  • 무의식적으로 사용하는 코드중 성능에 영향을 주는 Function call 요소
    • 인수, 함수의 주소, 메모리 로컬 상태에 함수 정보 할당

  • Call dispatch
    • static dispatch: 컴파일 타임에 우리가 호출하는 함수를 정확히 알 수 있는 경우 (성능 장점)
    • dynamic dispatch: 컴파일 타임에 우리가 호출하는 함수를 정확히 알 수 없는 경우 (다형성, 추상화 장점)
  • 대부분 잘못 알고 있는 주의사항)
    • protocol의 extension으로 선언하면 static dispatch로 동작함

ex) static dispatch 예시

protocol DataModel {
  func update(from source: DataSource, quickly: Bool)
}

extension DataModel {
  func update(from source: DataSource) {
    self.update(from: source, quickly: true)
  }
}

func updateAll (models: [any DataModel], from source: DataSource) {
  for model in models {
    model.update (from: source)
  }
}

ex) dynamic dispatch 예시

protocol DataModel {
  func update(from source: DataSource, quickly: Bool)
}

func updateAll (models: [any DataModel], from source: DataSource) {
  for model in models {
    model.update (from: source)
  }
}
  • Local allocation - 로컬 상태에 메모리를 할당하는 것
    • 아래 코드를 실행하면 내부적으로 c 스택 영역에 할당됨

컴파일 결과)

  • C 스택 영역에 208 byte를 할당

성능 2) memory allocation

  • Global memory
    • 프로그램이 시작하는 동시에 계속 남아있지만 사용하는곳은 특정 부분에만 사용될 것이므로 비효율적
    • ex) static 키워드, 전역으로 선언된 var, let 키워드
  • Stack memory
    • 메모리의 범위가 지정되어 있는 공간 (func과 같은 것들)
    • ex) local에 선언된 let, var 키워드, parameters
  • Heap memory
    • 유연한 메모리이며, 임의의 시간에 이를 할당하고 해제가 가능한 영역
    • 할당하고 해제할때 다른 메모리 영역보다 훨씬 더 비싼게 단점 
    • ex) class, actor instances
    • 종종 힙 메모리는 shared ownership (공동 소유권)을 갖음 (동일한 메모리에 대해 여러 개의 독립적인 참조를 갖는 형태)
  • cf) reference counting
    • heap memory에서 필요
    • reference-counting을 통해 heap 할당의 수명을 관리
    • retain: 참조 카운트를 늘리는 것
    •  

 

* 참고

https://developer.apple.com/videos/play/wwdc2024/10217

Comments