관리 메뉴

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

[iOS - swift] 메모리 프로파일링 - 맛보기 (메모리 관점에서의 UIImage 관리, 이미지 처리) 본문

iOS 응용 (swift)

[iOS - swift] 메모리 프로파일링 - 맛보기 (메모리 관점에서의 UIImage 관리, 이미지 처리)

jake-kim 2023. 12. 19. 01:57

* iOS 메모리 기초 개념은 Memory Deep Dive 포스팅 글 참고

기본 지식) 이미지의 중요한 요소 - 해상도

  • 이미지를 다룰때 중요한 것은 파일의 크기(volume)가 아닌 이미지의 크기(resolution)이라는 점을 알 것
  • 이미지를 구성하고 있는 pixcel관점에서, 1pixel을 이룰 때 RGB요소에 의해 각 1byte씩 3개가 필요하므로 3byte가 필요
    • 여기에다 alpha 채널까지 합하면 1pixel당 4byte가 필요
  • 만약 크기가 2048px * 1536px 의 이미지 파일 크기가 590KB가 디스크에 있을 때, 이 파일을 뷰에 표현할때는 약 10mb가 필요 (2048px * 1536px * 4byte)

UIImage 관리 - 이미지를 메모리에 잡고 있지 말 것

  • UIImage는 위에서 알아본대로 메모리에서 매우 큰 dirty memory를 차지하는 형태 
  • UIImage는 필요하지 않을때 메모리에서 내려야함
    • 메모리를 낮게 유지해야 좋은 이유는 이전 포스팅 글 참고

ex) background에 갈때는 UIImage를 nil로하고 foreground일때 다시 UIImage를 입력해주는 코드

func bind() {
    NotificationCenter.default.addObserver(
        forName: UIApplication.willEnterForegroundNotification,
        object: nil,
        queue: .main
    ) { [weak self] _ in
        self?.imageView.image = UIImage(named: "big_img")
    }
    
    NotificationCenter.default.addObserver(
        forName: UIApplication.didEnterBackgroundNotification,
        object: nil,
        queue: .main
    ) { [weak self] _ in
        self?.imageView.image = nil
    }
}

 

메모리 비교)

100MB -> 22.9MB로 변경되어 약 77.1MB 메모리가 세이브 된 상태

  • 주의할점
    • 보통 이미지를 선언할 때 전역변수에 UIImage를 선언해놓거나 상수 개념으로 선언해놓는데 이렇게하면 UIImageView.image에 nil을 대입해도 메모리가 해제되지 않으므로 전역에 선언해놓는 습관은 메모리 관리 차원에서 좋지 않은 케이스

ex) 전역변수에 UIImage를 선언한 경우 image가 dirty memory에 상주하고 있는 상태

* 전체 코드: https://github.com/JK0369/ExMemoryProfileing

* 참고

https://commons.wikimedia.org/wiki/File:%22Aunt_Bessie%27s%22_home._Washington,_D.C.,_Oct._29._This_unimposing_apartment_house_will_no_doubt_be_the_scene_of_a_visit_from_the_Duke_and_Duchess_of_Windsor_when_they_come_to_the_National_LCCN2016872497.jpg

Comments