Section 5/221 menit

5. Optimasi Swift Compiler

5. Optimasi Swift Compiler

Anotasi Tipe Eksplisit di Hot Paths

Prioritaskan anotasi tipe pada:

  1. Properti @State, @Published, @ObservedObject di SwiftUI
  2. Return type fungsi yang dipanggil dari banyak tempat
  3. Computed property yang kompleks
  4. Variabel dalam loop
swift
// ❌ LAMBAT: compiler inference pada setiap penggunaan
var body: some View {
    let filtered = viewModel.items
        .filter { !$0.isDeleted }
        .sorted { $0.createdAt > $1.createdAt }

    return List(filtered) { item in
        ItemRow(item: item)
    }
}

// ✓ CEPAT: tipe eksplisit membantu compiler
var body: some View {
    let filtered: [Item] = viewModel.items
        .filter { !$0.isDeleted }
        .sorted { $0.createdAt > $1.createdAt }

    return List(filtered, id: \.id) { (item: Item) in
        ItemRow(item: item)
    }
}

Pecah Expression Kompleks

swift
// ❌ LAMBAT: satu expression panjang, inference berjalan dari dalam ke luar
let config = URLRequest(
    url: URL(string: baseURL + "/api/v2/" + endpoint + "?" + params.map { "\($0.key)=\($0.value)" }.joined(separator: "&"))!
)

// ✓ CEPAT: pisahkan langkah-langkah dengan tipe eksplisit
let queryString: String = params.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
let urlString: String = "\(baseURL)/api/v2/\(endpoint)?\(queryString)"
let url: URL = URL(string: urlString)!
var config = URLRequest(url: url)

Hindari AnyView yang Tidak Perlu di SwiftUI

AnyView menghapus informasi tipe, memaksa compiler melakukan type erasure — lebih lambat dibanding view generics.

swift
// ❌ LAMBAT: AnyView menyembunyikan tipe, compiler lebih banyak kerja
func makeRow(for item: Item) -> AnyView {
    if item.isPremium {
        return AnyView(PremiumRow(item: item))
    } else {
        return AnyView(StandardRow(item: item))
    }
}

// ✓ CEPAT: @ViewBuilder mempertahankan informasi tipe
@ViewBuilder
func makeRow(for item: Item) -> some View {
    if item.isPremium {
        PremiumRow(item: item)
    } else {
        StandardRow(item: item)
    }
}

Batasi Penggunaan Protocol dengan Associated Types

PAT (Protocol with Associated Types) dan generics kompleks adalah kontributor terbesar waktu kompilasi Swift.

swift
// ❌ BISA LAMBAT di project besar: terlalu banyak generic constraint
func process<T: Collection, U: Hashable & Comparable>(
    items: T,
    groupBy keyPath: KeyPath<T.Element, U>
) -> [U: [T.Element]] where T.Element: Identifiable {
    Dictionary(grouping: items, by: { $0[keyPath: keyPath] })
}

// ✓ LEBIH CEPAT untuk use case konkret: gunakan tipe konkret
func groupItems(_ items: [Item], by category: KeyPath<Item, String>) -> [String: [Item]] {
    Dictionary(grouping: items, by: { $0[keyPath: category] })
}