Background: Why is Swift “slow”? 3. Techniques: How to write compiler-friendly code 1. Pro fi le! Pro fi le!! Pro fi le!!! 2. Reduce dynamic dispatch 3. Reveal hidden CoW cost 4. Value operation cost
func bark() {} } class Cat: Animal { override func bark() { print("meow") } } let cat = Cat() let animal = cat as Animal animal.bark() Q. Where retain/release will be placed?
open class Animal { open func bark() {} } func useAnimal(_ x: Animal) { x.bark() // Animal.bark can be overridden outside the module } • Check if compiler can know the callee method at compile-time 🧐 • Use small type as much as possible (Cat < Animal < Any) Class instance methods
the struct type is trivial • Trivial Types (POD: Plain Old Data): No extra copy, move, destruction semantics • Int, Bool, Double, … • A struct type that consists of trivial types • Many container types in stdlib (Array, Set, …) has fast-path for trivial types • Optimized to be a memcpy
// false struct Box<T> { let value: T } print(_isPOD(Box<Int>.self)) // true print(_isPOD(Box<String>.self)) // false Check a type is trivial or not by _isPOD
short code • Understanding the underlying mechanism makes your code fast! • The GoodNotes’ Ink algorithm is now 7x faster! Before After 0 150 300 450 600 Benchmark Time (ms)