Git Product home page Git Product logo

cozzin.github.io's People

Contributors

cozzin avatar dependabot[bot] avatar

Stargazers

 avatar

Watchers

 avatar

cozzin.github.io's Issues

TO DO: iOS 기초

[WWDC21] Ultimate application performance survival guide

https://developer.apple.com/videos/play/wwdc2021/10181/

툴이 되게 많음
image

자 이렇게 따라가 봅시다
image

Battery usage

  • 배터리 관리를 잘해줘야 앱도 오래 머물 수 있음
  • CPU, Networking, Location, GPU, Audio, Bluetooth 신경 써야함

스프레이 버튼 > Energy Impact 들어가서 Energy Impact 확인할 수 있음

image

image

MetricKit

원격 측정 프레임워크. 릴리즈된 앱을 측정하는데 도움이 될 수 있음
image

class AppMetrics: MXMetricManagerSubscriber {
	init() {
		let shared = MXMetricManager.shared
		shared.add(self)
	}

	deinit {
		let shared = MXMetricManager.shared
		shared.remove(self)
	}

	// Receive daily metrics
	func didReceive(_ payloads: [MXMetricPayload]) {
		// Process metrics
	}

	// Receive diagnostics
	func didReceive(_ payloads: [MXDiagnosticPayload]) {
		// Process metrics
	}
}

앱 사용 퍼포먼스 -> 애플 서버에 전달됨 -> Xcode Organizer에서 볼 수 있음

image

Organizer 켜면 Battery Usage 확인할 수 있음. 최근 16개 버전 볼 수 있음

image

Regression Pane
image

어떤 부분이 이슈를 만들어내는지 보려면, Report 아래에 있는 Energy Organizer를 보면 됨
image

배터리 성능 측정에 대해 더 알아보기

Hang rate and scrolling

  • Hang은 앱이 250밀리초 이상 사용자 입력 또는 작업에 응답하지 않는 경우

여기서 빨간 막대는 스크롤 경험이 안좋을 수록 표시됨 (렉 걸리는 그 느낌...)
image

Instruments로 어느 부분이 Hang을 일으키는지 분석할 수 있음

image

스크롤 경험을 XCTest로 측정할 수 있음

func testScrollingAnimationPerformance() throws {
        
    app.launch()
    app.staticTexts["Meal Planner"].tap()
    let foodCollection = app.collectionViews.firstMatch

    let measureOptions = XCTMeasureOptions()
    measureOptions.invocationOptions = [.manuallyStop] // 이렇게 지정하면 블록 중간에 stopMeasuring 지정할 수 있음
        
    measure(metrics: [XCTOSSignpostMetric.scrollDecelerationMetric], // 스크롤 측정
    options: measureOptions) {
        foodCollection.swipeUp(velocity: .fast) // start 
        stopMeasuring()
        foodCollection.swipeDown(velocity: .fast) // reset
    }
}

MetricKit을 구성하면 iOS 14에서는 24시간 간격으로 원격 이슈 파악 가능하고
image

iOS 15에서는 즉시 이슈 파악 가능함...!!!!
image

func startAnimating() {
	// Mark the beginning of animations
	mxSignpostAnimationIntervalBegin(
		log: MXMetricManager.makeLogHandle(category: "animation_telemetry"), 
		name: "custom_animation”)
}

func animationDidComplete() {
	// Mark the end of the animation to receive the collected hitch rate telemetry
	mxSignpost(OSSignpostType.end, 
		log: MXMetricManager.makeLogHandle(category: "animation_telemetry"), 
		name: "custom_animation")
}

더 알아보기
Understand and eliminate hangs from your app, WWDC21 - https://developer.apple.com/videos/play/wwdc2021/10258/

Disk Writes

Instruments 통해서 Disk I/O 확인할 수 있음
image

Disk Usage를 XCTest로 측정할 수 있음
baseline를 설정해서 그것보다 퍼포먼스가 안나오면 테스트 실패되게 만들 수 있음

// Example performance XCTest

func testSaveMeal() {
	let app = XCUIApplication()
	let options = XCTMeasureOptions()
	options.invocationOptions = [.manuallyStart]

	measure(metrics: [XCTStorageMetric(application: app)], options: options) {
		app.launch()
		startMeasuring()

		let firstCell = app.cells.firstMatch
		firstCell.buttons["Save meal"].firstMatch.tap()

		let savedButton = firstCell.buttons["Saved"].firstMatch
		XCTAssertTrue(savedButton.waitForExistence(timeout: 2))
	}
}

이미 출시된 버전은 Organizer를 통해 확인 가능

image

Report 섹션 아래의 Disk Writes
앱이 24시간 내에 1GB 이상 디스크 쓰기를 하면 Report
image

Xcode13 에서는 어떻게 고쳐야할지 Insights 를 제공함.
image

Disk Write 이슈 더 알아보기:
Diagnose power and performance regressions in your app, WWDC21 - https://developer.apple.com/videos/play/wwdc2021/10087/

Launch time and termination

  • 실행 시간: 실행 시간이 길면 유저는 짜증남...
  • 종료 관리: 앱이 종료되게 되면 앱을 다시 사용할 떄도 실행하는 시간이 또 걸림

Organizer > Launch time
image

Organizer > Termination
image

Instruments > App Launch
image

앞서 본 것 처럼 XCTest를 활용할 수도 있음

MetricKit이 앱에 구현되어 있으면 daily metric payload로 매일 받아볼 수 있음

왜 앱이 종료되는지 자세히 확인하고 싶다면?
Why is my app getting killed?, WWDC 20 - https://developer.apple.com/videos/play/wwdc2020/10078/

Memory

Organizer > Memory
image

Instruments > Leaks, Allocations, VM Tracker
image

MetricKit

// Collect memory telemetry

func saveAppAssets() {
	mxSignpost(OSSignpostType.begin, 
		log: MXMetricManager.makeLogHandle(category: "memory_telemetry"), 
		name: "custom_memory")

	// save app metadata

	mxSignpost(OSSignpostType.end, 
		log: MXMetricManager.makeLogHandle(category: "memory_telemetry"), 
		name: "custom_memory")
}

더 알아보기:
Detect and diagnose memory issues #36
https://developer.apple.com/videos/play/wwdc2021/10180/

Next step

image

[WWDC21] What's new in Swift

Update on Swift packages

Swift Package Collection

image
image

  • 패키지를 검색해서 찾기 쉬움
  • CocoaPods Specs 같은 느낌

Data Sturcture

Swift Collections

Deque

image

  • Array 같은건데, 양쪽 끝으로 삽입 삭제가 가능

OrderedSet

image

  • 순서가 있는 Set
  • Random Access도 가능
  • Set 이랑 동일하게 Element가 하나만 있는 걸 보장해줌

OrderDictionary

image

  • 순서대로 접근 가능
  • Random Access도 가능

Algorithms

image

  • extension으로 구현해서 쓰던게 이제 기본으로 많이 제공되는 듯
  • (코테 칠때 편할듯)

https://developer.apple.com/videos/play/wwdc2021/10256/

Swift System

FilePath

image
image
image

  • window path가 뭐지? Root도 지정할 수 있는 간편한 방법을 제공

Swift Numerics

작년에 Float16 타입 도입되었는데, 이번에 Apple Silicon에 Float16에도 추가됨.

  • Float16-based complex number 구성 가능
  • Complex: 로그, 사인, 코사인 표현 가능

image

ArgumentParser

  • Fish shell completion scripts
  • Joined short options (-Ddebug)
  • Improved error messages

이런거 보면 Swift로 만든 스크립트 작성이 편할 듯

Swift Server

image

  • Static linking on Linux
  • Imporved JSON performance
  • Enhanced AWS Lambda runtime: 아무튼 빠름

image

Developer experience improvements

Swift DocC

image

Type checker 퍼포먼스 개선

image
이제는 이런 에러들 없음!

Build Improvements

  • imported modules이 변경되었을 때 빌드 속도 빨라짐
  • compile 시작전 시간 빨라짐
  • extension 코드가 변경되었을때 재컴파일 적게함

image
image

Memory Management

  • 더 효율적으로 관리

image

Ergonomic improvements

image

Result Builders

Enum Codable synthesis

image
간편하게 Codable 구현 가능

Flexible static member lookup

Protocol에 static var로 확장해두면 사용하는 곳에서 간편하게 사용 가능.
Screenshot 2021-07-10 PM 5 20 18

Property wrappers on parameters

파라미터로 사용 가능!
image

코드 개선해보기

기존

image

개선

image

https://developer.apple.com/videos/play/wwdc2021/10018/

Asynchronous and concurrent programming

image

코드 살펴보기

기존

image

개선

image
제어 흐름이 위에서 아래로 흘러서 이해하기 쉬움

Structured Concurrency

기본

image

병렬

image
async 키워드 하나면 가능

Actor

멀티 스레딩 이슈

image
여러 스레드에서 동작하면 이슈가 됨

Actor 사용

image
actor를 사용하면 스레드 이슈가 없어짐

image
await 쓸때 일반적으로 필요하다는 뜻

image
async/await 도 잘 동작함

actor는 클래스와 같이 reference type임
하지만 멀티 스레드에서 안전하게 사용할 수 있도록 규칙이 적용됨

Protect mutable state with Swift actors

Looking ahead to Swift6

  • Safe Concurrency 동시성 이슈에 초집중할듯!
  • 스위프트 포럼에 참여해달라!

CollectionView Prefetching

  1. UICollectionView Prefetching 과정 볼 수있는 view 만들기
    https://developer.apple.com/documentation/uikit/uicollectionviewdatasourceprefetching/prefetching_collection_view_data 참고

  2. Prefetching 안한 버전

  3. Prefetching 한 버전

  • Prefecthing시에 Unsplash 같은데서 이미지 가져온 다음 보여주는 방식으로 만들면 좋을 듯.
    https://github.com/TaeJoongYoon/FlickrSearch 참고

  • 2, 3번 수치로 비교할 수 있으면 좋겠다. 어떤식으로 비교할 수 있을까?

Detect and diagnose memory issues

https://developer.apple.com/videos/play/wwdc2021/10180/

1. Impact of memory footprint

1-1. 왜 memory footprint를 신경써야하나?

사용자 경험을 극대화하기 위해서!

  • 빠른 앱 활성화
  • 빠른 반응
  • 복잡한 기능 제공
  • 오래된 디바이스도 지원

1-2. Memory footprint

근데 이건 도대체 뭘까?! Dirty + Compressed memory!!

image

  • Dirty: 앱에서 사용된 메모리, 모든 heap allocations, Decoded image buffers, Frameworks
  • Compreesed: 최근 access 되지 않은 dirty memory를 압축해둔 페이지. access 하면 압축이 풀림. (macOS에 적용)
  • Clean: 아직 쓰지 않았거나 페이징 할 수 있음. 디스크에 있지만 메모리에 로드하지 않은 것들.

더 알아보기: iOS Memory Deep Dive - https://developer.apple.com/wwdc18/416

2. Tools for profiling memory

image

  • XCTest: Unit & UI 테스트에서 메모리 공간을 직접 확인 가능
  • MetricKit, Xcode Organizer: 유저의 운영 환경에서 memory metrics를 모니터링 할 수 있음.
    • memory metrics는 무엇? 검색해보니 측정된 지표 같음... 아는 분 있나요?

🟢 2-1. Performance XCTests

  • 메모리 사용, CPU 사용, 디스크 쓰기 측정 가능
// Monitor memory performance with XCTests

func testSaveMeal() {
    let app = XCUIApplication()
        
    let options = XCTMeasureOptions()
    options.invocationOptions = [.manuallyStart]
        
    measure(metrics: [XCTMemoryMetric(application: app)], // 타겟 앱 지정
            options: options) {

        app.launch()

        startMeasuring() // ⏱ 측정 시작!

        app.cells.firstMatch.buttons["Save meal"].firstMatch.tap()
            
        let savedButton = app.cells.firstMatch.buttons["Saved"].firstMatch
        XCTAssertTrue(savedButton.waitForExistence(timeout: 30)) // 측정을 위해 30초 기다림
    }
}

결과 확인

그러고 나면 테스트 옆에 회색 다이아몬드를 눌러서 결과를 확인할 수 있음

Metric 고르기

image

각 iteration 당 측정된 결과 확인

image

Baseline 지정

평균 값을 baseline으로 지정할 수 있음 -> 다음 테스트와 비교할 수 있음

image

테스트 실패

baseline 보다 높게 나올 경우 테스트 페일됨. 이 지표는 언제 멈추고 코드를 수정해야할지 알려줌.
baseline 부터의 편차를 regression 이라고 부름.

image

Diagnostic collection in XCTests (Xcode 13 신기능 👀)

앞서 나온 regression 분석을 위한 새로운 도구가 나왔음
Ktrace files, Memory graphs.

image

Ktrace files: 일반적인 시스템 조사, 렌더링 파이프라인 파악, 메인 쓰레드 행 걸리는 이유 분석 등 다양하게 쓸 수 있음

image

더 알아보기

🕸 2-2. Memory Graph

Visual debugger로 볼 수도 있지만 command line 으로도 확인할 수 있음

image

Enable diagnostic collection

아직 뭔지 잘 모르겠음...ㅠ command line 에서 이렇게 활성화 시킬 수 있음.
이렇게 해두면 nonmemroy metric에 대한 ktrace collection과 memory metrc에 대한 memgrph를 사용할 수 있다.
image

테스트 결과

콘솔에 출력는게 많은데 그 중에 주목할 것들은...

테스트 통과 여부

image

테스트 실패 이유

예제에서는 퍼포먼스 baseline 기준을 넘지 못했음
image

xcresult 파일

image

xcresult 열어보기

첨부된 memgraph가 있음!
image

zip 파일 열어보면

  • memgraph가 2개 있음
  • malloc 스택 로깅을 위해서 iteration을 한번 더 실행하기 떄문
  • 그래서 필요하다면 iteration 간의 메모리 증가를 분석할 수 있음
    image

3. Types of memory issues

자 이렇게 추출한 파일을 보고 메모리 이슈를 분석해봅시다
Leak, Heap size issue 이슈를 살펴봄

Command line tool로 메모리 분석하는 거 더 찾아보려면...
iOS Memory Deep Dive - https://developer.apple.com/wwdc18/416

3-1. Leaks

객체를 allocate 하고 deallocate 하지 않은 채로 모든 reference를 잃어버리면 발생함

Leak 발생 원리

image

image

image

Retain cycle

image

memgraph 파일로 이슈 살펴보기

image

image

몇개의 leak이 발생했는지 분석해줌. 아래에는 좀 더 자세한 callstack이 나와있음
image

우리 앱에 있는 심볼을 발견할 때가 있음
image

코드를 들어가보면 서로 참조 하고 있음 :)
image

한쪽을 weak으로 바꿔주기
image

(뭔가 엄청난 가이드가 나올줄 알았는데 별건 아니었음...)

3-2. Heap size issues: Heap allocation regressions

힙 공간에 이전보다 많은 메모리를 할당하는 이슈

실패한 XCTest로 돌아가서 살펴보자
어디를 봐야할지 확인하기 위해서 vmmap -summary 를 입력해봄.
pre memgraph랑 post memgraph를 비교

image

13 MB 차이가 남!
image image

스크롤을 좀 더 내려봄.
프로세스의 메모리 사용이 region 별로 나눠져 있음
image

Heap allocation issue 라고 추정되기 떄문에 MALLOC_ region을 살펴보겠음
image

앞에 나왔던 설명 돌아보면
memory footprint = dirty memory + compressed memory 니까, 아래의 두 열을 보면됨.
(compressed = swapped 같은 의미)
image

MALLOC_LARGE region에 대략 13 MB의 dirty memory가 있음 = 아주 강한 의심이 간다
image

어떤 object가 관여하는지 더 정확하게 파악해보자
heap -diffFrom 을 실행!

image

post 에는 있지만 pre memgraph 에는 없는 것들이 출력됨
좀 내려보면 메모리를 object 단위로 나눠놓은게 있음.
object의 개수, bytes 볼 수 있음
image

맨 위에 non-object가 13 MB 정도 차지하는 것을 볼 수 있음ㅠ
Swift에서 주로 raw malloced bytes를 의미함 (뭐지...?)

non-object가 뭔지 파악하는 방법도 있음!!
heap -address 명령어를 입력해서 분석. 최소 500kb의 non-object만 찾도록 지정

image

유력한 용의자... 이 주소값을 가지고 다시 찾아보자
image

몇 가지 방법이 있음

leaks --traceTree

특정 객체에 대한 정보는 없고 주소값만 있을 때 사용해 볼 수 있음
image

아마도 MKTCustomMeal PlannerCollectionViewCell 과 관련이 있어보임
image

leaks --referenceTree

모든 메모리의 top-down reference를 보여줌
image

--groupByType 옵션 주면 좀 더 보기 편할 수 있음
image

malloc_history -fullStacks

이 object가 어떻게 allocate되었는지 파악할 수 있음
image

여기서 allocate 되었음을 파악할 수 있다
image

코드 수정

mealData는 saveMeal 되고나면 필요없는데 Cell이 유지되는 동안은 계속 남아있게 됨
image

saveMeal 이후에 mealData를 nil 처리 하는 방안이 있음
image

3-3. Heap size issues: Fragmentation (조각화, 파편화)

iOS에서의 Page 작동원리

  • Page: 프로세스를 위한 메모리 유닛의 최소 단위
  • 페이지는 나눌 수 없기 떄문에, 페이지의 어느 부분에든 쓰게 되면 dirty page로 간주됨. 페이지가 조금만 사용되어도 dirty가 됨.
    image

Fragmentation

  • 100% 사용되지 않는 dirty page가 있는 경우 발생

처음엔 Clean
image

프로세스가 작동하면서 Allocated object가 page를 채움
image

일부 Object가 deallocate 되면서 free memory가 됨.
하지만 여전히 allocated object가 있기 떄문에 여전히 dirty page.
image

시스템은 이 빈공간을 채우려고 함.
파란색 크기의 allocation이 있다고 가정함.
빈공간을 합쳐보면 파란색 allocation을 받아줄 수 있지만, 한번에 allocate할 공간은 없음
image

기존의 슬롯을 활용할 수 없기 때문에, 새로운 dirty page를 사용하게 되었음.
이렇게 free memory가 부분적으로 남아있는 경우를 Fragmentation 이라고 함
image

fragmentation을 줄이기 위해서는
메모리에서 유사한 lifetime을 가진 object끼리 allocate 하는 것이 가장 좋은 방법

동일한 Object는 모아서 allocate
image

이러면 Object가 deallocate 되었을 때 Clean Page를 확보할 수 있음
image

실제 시나리오에서는

  • fragmentation이 불가피함
  • 조금 더 줄이는 것에 목표를 두는 것이 좋음
  • autorelease pool을 사용하자
  • 장시간 작동하는 프로세스는 주의를 기울이자

이슈 살펴보기

vmmap -summary 입력해서 볼 수 있음
image

DIRTY+SWAP FRAG SIZE를 보면 정확히 낭비되는 공간을 볼 수 있음
image

Instruments Tool > Allocations
image

Allocation List, Created & Destroyed를 체크해서 확인
image

image

Instruments tool 사용을 좀 더 알아보려면 -> Getting Started with Instruments

Detect

모니터링

새 기능 추가 후에도 XCTest를 작성하여 지속적으로 퍼포먼스를 모니터링 할 수 있음
image

이슈 분석

image

SwiftyBeaver

Your project uses SwiftyBeaver. SwiftyBeaver has security vulnerabilities that you may wish to address. Consider removing SwiftyBeaver if your app transmits PII. SwiftyBeaver/SwiftyBeaver#453

objc_setAssociatedObject

https://github.com/jieumjigi/si-eum-iOS/blob/develop/sieum/UIControl%2BExtension.swift

extension UIGestureRecognizer {
    convenience init(_ onEvent: @escaping () -> Void) {
        let sleeve = ClosureSleeve(onEvent)
        self.init(target: sleeve, action: #selector(ClosureSleeve.invoke))
        objc_setAssociatedObject(self, "\(arc4random())", sleeve, .OBJC_ASSOCIATION_RETAIN)
    }
}

extension의 사용과 함께 objc_setAssociatedObject를 사용하게 되는데
참조가 제대로 해제되는지 언제 해제되는지 체크하는 실험 필요함.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.