Chapter 3. Protocols 의 후속 공부
<aside>
📌 목차
1. Allocation
- Stack allocation is very fast; the cost of assigning an integer.
- Heap is more dynamic but less efficient, O(log n).
- Also needs to protect integrity by checking for thread safety which is lots of overhead.
- 힙은 모든 쓰레드에서 접근할 수 있다.
- 따라서 integrity 관리를 해줘야한다.
= 연산자에서의 차이
- struct : 새로운 복사본(copy) 를 만들어낸다.
- class: 새로운 reference 를 만든다. 이 reference 는 힙 메모리를의 동일한 인스턴스를 가리킨다.
→ heap allocation 은 비싼 동작이다.
아래 코드를 보자
enum Color {
case blue, green, gray
}
enum Orientation {
case left, right
}
enum Tail {
case none, tail, bubble
}
// Never construct something more than once; if you need it again, it’s already here.
var cache = [String: UIImage]()
func makeBalloon(_ color: Color, orientation: Orientation, tail: Tail) -> UIImage {
// Add
let key = “\\(color):\\(orientation):\\(tail)”
if let image = cache[key] {
return image
}
// If not cached, make a new balloon...
}
what’s bad?
- A String is not a strong key
- A String is almost limitless
- 우리집 강아지의 이름을 키로 사용할 수도 있다.
- 어떤 문자열이든 Key 가 될 수 있으므로 강력한 키가 아니다.
- 제한이 없다는 점에서 강력하지 않다고 하는 것 같다.
- String stores the contents of its characters indirectly on the heap.
UIImage
를 캐싱하여 heap allocation 을 줄였지만, 한편으로는 Key 로 String
을 사용하므로 heap allocation 이 계속 일어나고 있음이 안좋다는 것!
How can you make this better?
- Key 를 struct 로 사용한다. Hashable 을 채택시키면 키로 사용할 수 있다.