mcpField
P
performance-optimization

performance-optimization

github.com/kaakati开发1036 次安装39 周前更新
代码仓库

关于 performance-optimization

performance-optimization 是面向 Swift 和 SwiftUI 应用开发者的性能决策指南,强调先分析再修改代码,并提供界面更新、内存管理、图像加载和后台任务模式。

主要功能

  1. 01性能分析工具选择指导
  2. 02SwiftUI 视图更新策略
  3. 03内存泄漏与缓存实践
  4. 04图像降采样模式
  5. 05后台任务建议

适用场景

  1. 01调查界面卡顿或掉帧
  2. 02追踪内存增长和循环引用
  3. 03减少 SwiftUI 视图的重复计算
  4. 04在内存限制下加载缩略图

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kaakati/rails-enterprise-dev --skill performance-optimization

安装后在 Claude Code 中输入/performance-optimization确认已加载。

附带文件references/complete-performance-toolkit.md

详细介绍

性能优化——专家决策

针对性能选择的专家决策框架。Claude 了解延迟加载和异步处理的基础知识——本技能提供有关何时优化以及选择哪种工具的判断建议。


决策树

是否应该优化?
When should you invest in optimization?
├─ User-facing latency issue (visible stutter/delay)
│  └─ YES — Profile and fix
│     Measure first, optimize second
│
├─ Premature concern ("this might be slow")
│  └─ NO — Wait for evidence
│     Write clean code, profile later
│
├─ Battery drain complaints
│  └─ YES — Use Energy Diagnostics
│     Focus on background work, location, network
│
├─ Memory warnings / crashes
│  └─ YES — Use Allocations + Leaks
│     Find retain cycles, unbounded caches
│
└─ App store reviews mention slowness
   └─ YES — Profile real scenarios
      User perception matters

陷阱:基于假设进行优化。务必先进行性能分析。瓶颈很少出现在你认为的位置。

性能分析工具选择
What are you measuring?
├─ Slow UI / frame drops
│  └─ Time Profiler + View Debugger
│     Find expensive work on main thread
│
├─ Memory growth / leaks
│  └─ Allocations + Leaks instruments
│     Track object lifetimes, find cycles
│
├─ Network performance
│  └─ Network instrument + Charles/Proxyman
│     Latency, payload size, request count
│
├─ Disk I/O issues
│  └─ File Activity instrument
│     Excessive reads/writes
│
├─ Battery drain
│  └─ Energy Log instrument
│     CPU wake, location, networking
│
└─ GPU / rendering
   └─ Core Animation instrument
      Offscreen rendering, overdraw
SwiftUI 视图更新策略
View is re-rendering too often?
├─ Caused by parent state changes
│  └─ Extract to separate view
│     Child doesn't depend on changing state
│
├─ Complex computed body
│  └─ Cache expensive computations
│     Use ViewModel or memoization
│
├─ List items all updating
│  └─ Check view identity
│     Use stable IDs, not indices
│
├─ Observable causing cascading updates
│  └─ Split into multiple @Published
│     Or use computed properties
│
└─ Animation causing constant redraws
   └─ Use drawingGroup() or limit scope
      Rasterize stable content
内存管理决策
How to fix memory issues?
├─ Steady growth during use
│  └─ Check caches and collections
│     Add eviction, use NSCache
│
├─ Growth tied to navigation
│  └─ Check retain cycles
│     weak self in closures, delegates
│
├─ Large spikes on specific screens
│  └─ Downsample images
│     Load at display size, not full resolution
│
├─ Memory not released after screen dismissal
│  └─ Debug object lifecycle
│     deinit not called = retain cycle
│
└─ Background memory pressure
   └─ Respond to didReceiveMemoryWarning
      Clear caches, release non-essential data

绝对不要做

视图标识

绝对不要使用索引作为标识符:

// ❌ Identity changes when array mutates
List(items.indices, id: \.self) { index in
    ItemRow(item: items[index])
}
// Insert at index 0 → all views recreated!

// ✅ Use stable identifiers
List(items) { item in
    ItemRow(item: item)
        .id(item.id)  // Stable across mutations
}

绝对不要在 body 中计算开销大的值:

// ❌ Called on every render
var body: some View {
    let sortedItems = items.sorted { $0.date > $1.date }  // O(n log n) per render!
    let filtered = sortedItems.filter { $0.isActive }

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

// ✅ Compute in ViewModel or use computed property
@MainActor
class ViewModel: ObservableObject {
    @Published var items: [Item] = []

    var displayItems: [Item] {
        items.filter(\.isActive).sorted { $0.date > $1.date }
    }
}
状态管理

绝对不要对传入的对象使用 @StateObject:

// ❌ Creates new instance on every parent update
struct ChildView: View {
    @StateObject var viewModel: ChildViewModel  // Wrong!

    var body: some View { ... }
}

// ✅ Use @ObservedObject for passed objects
struct ChildView: View {
    @ObservedObject var viewModel: ChildViewModel  // Parent owns it

    var body: some View { ... }
}

绝对不要将所有属性都设为 @Published:

// ❌ Every property change triggers view updates
class ViewModel: ObservableObject {
    @Published var items: [Item] = []
    @Published var internalCache: [String: Data] = [:]  // UI doesn't need this!
    @Published var isProcessing = false  // Maybe internal only
}

// ✅ Only publish what UI observes
class ViewModel: ObservableObject {
    @Published var items: [Item] = []
    @Published var isLoading = false

    private var internalCache: [String: Data] = [:]  // Not @Published
    private var isProcessing = false  // Private state
}
内存泄漏

绝对不要在逃逸闭包中强引用 self:

// ❌ Retain cycle — never deallocates
class ViewModel {
    var timer: Timer?

    func start() {
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            self.tick()  // Strong capture!
        }
    }
}

// ✅ Weak capture + invalidation
class ViewModel {
    var timer: Timer?

    func start() {
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            self?.tick()
        }
    }

    deinit {
        timer?.invalidate()
    }
}

绝对不要忘记移除观察者:

// ❌ Leaks observer and potentially self
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleNotification),
            name: .userLoggedIn,
            object: nil
        )
        // Never removed!
    }
}

// ✅ Remove in deinit or use modern API
class ViewController: UIViewController {
    private var observer: NSObjectProtocol?

    override func viewDidLoad() {
        super.viewDidLoad()
        observer = NotificationCenter.default.addObserver(
            forName: .userLoggedIn,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.handleNotification()
        }
    }

    deinit {
        if let observer { NotificationCenter.default.removeObserver(observer) }
    }
}
图像加载

绝对不要为缩略图加载全分辨率图像:

// ❌ 4000×3000 image for 80×80 thumbnail
let image = UIImage(contentsOfFile: path)  // Full resolution in memory!
imageView.image = image

// ✅ Downsample to display size
func downsampledImage(at url: URL, to size: CGSize) -> UIImage? {
    let options: [CFString: Any] = [
        kCGImageSourceShouldCache: false,
        kCGImageSourceCreateThumbnailFromImageAlways: true,
        kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) * UIScreen.main.scale
    ]

    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
          let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {
        return nil
    }
    return UIImage(cgImage: cgImage)
}

绝对不要不加限制地缓存图像:

// ❌ Unbounded memory growth
class ImageLoader {
    private var cache: [URL: UIImage] = [:]  // Grows forever!

    func image(for url: URL) -> UIImage? {
        if let cached = cache[url] { return cached }
        let image = loadImage(url)
        cache[url] = image  // Never evicted
        return image
    }
}

// ✅ Use NSCache with limits
class ImageLoader {
    private let cache = NSCache<NSURL, UIImage>()

    init() {
        cache.countLimit = 100
        cache.totalCostLimit = 50 * 1024 * 1024  // 50 MB
    }

    func image(for url: URL) -> UIImage? {
        if let cached = cache.object(forKey: url as NSURL) { return cached }
        guard let image = loadImage(url) else { return nil }
        cache.setObject(image, forKey: url as NSURL, cost: image.jpegData(compressionQuality: 1)?.count ?? 0)
        return image
    }
}
开销大的操作

绝对不要在主线程执行开销大的工作:

// ❌ UI frozen during processing
func loadData() {
    let data = try! Data(contentsOf: largeFileURL)  // Blocks main thread!
    let parsed = parseData(data)  // Still blocking!
    self.items = parsed
}

// ✅ Use background thread, update on main
func loadData() async {
    let items = await Task.detached(priority: .userInitiated) {
        let data = try! Data(contentsOf: largeFileURL)
        return parseData(data)
    }.value

    await MainActor.run {
        self.items = items
    }
}

核心模式

高效列表视图
struct EfficientListView: View {
    let items: [Item]

    var body: some View {
        ScrollView {
            LazyVStack(spacing: 12) {  // Lazy = on-demand creation
                ForEach(items) { item in
                    ItemRow(item: item)
                        .id(item.id)  // Stable identity
                }
            }
        }
    }
}

// Equatable row prevents unnecessary updates
struct ItemRow: View, Equatable {
    let item: Item

    var body: some View {
        HStack {
            AsyncImage(url: item.imageURL) { image in
                image.resizable().aspectRatio(contentMode: .fill)
            } placeholder: {
                Color.gray.opacity(0.3)
            }
            .frame(width: 60, height: 60)
            .clipShape(RoundedRectangle(cornerRadius: 8))

            VStack(alignment: .leading) {
                Text(item.title).font(.headline)
                Text(item.subtitle).font(.caption).foregroundColor(.secondary)
            }
        }
    }

    static func == (lhs: ItemRow, rhs: ItemRow) -> Bool {
        lhs.item.id == rhs.item.id &&
        lhs.item.title == rhs.item.title &&
        lhs.item.subtitle == rhs.item.subtitle
    }
}
内存安全的 ViewModel
@MainActor
final class ViewModel: ObservableObject {
    @Published private(set) var items: [Item] = []
    @Published private(set) var isLoading = false

    private var cancellables = Set<AnyCancellable>()
    private var loadTask: Task<Void, Never>?

    func load() {
        loadTask?.cancel()  // Cancel previous

        loadTask = Task {
            guard !Task.isCancelled else { return }

            isLoading = true
            defer { isLoading = false }

            do {
                let items = try await API.fetchItems()
                guard !Task.isCancelled else { return }
                self.items = items
            } catch {
                // Handle error
            }
        }
    }

    deinit {
        loadTask?.cancel()
        cancellables.removeAll()
    }
}
防抖搜索
@MainActor
final class SearchViewModel: ObservableObject {
    @Published var searchText = ""
    @Published private(set) var results: [Item] = []

    private var searchTask: Task<Void, Never>?

    init() {
        // Debounce search
        $searchText
            .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
            .removeDuplicates()
            .sink { [weak self] text in
                self?.performSearch(text)
            }
            .store(in: &cancellables)
    }

    private func performSearch(_ query: String) {
        searchTask?.cancel()

        guard !query.isEmpty else {
            results = []
            return
        }

        searchTask = Task {
            do {
                let results = try await API.search(query: query)
                guard !Task.isCancelled else { return }
                self.results = results
            } catch {
                // Handle error
            }
        }
    }
}

快速参考

Instruments 选择
问题工具关注点
UI 卡顿Time Profiler主线程上的繁重工作
内存泄漏Leaks泄漏的对象
内存增长Allocations持续增长的类别
电池耗电Energy Log唤醒频率
网络Network请求数量、大小
磁盘File Activity过多的 I/O
GPUCore Animation离屏渲染
SwiftUI 性能检查清单
问题解决方案
列表滚动缓慢使用 LazyVStack/LazyVGrid
所有项都重新渲染稳定 ID、遵循 Equatable 的行视图
body 计算开销大移至 ViewModel
@Published 更新连锁触发拆分或使用计算属性
动画卡顿使用 drawingGroup()
内存管理
模式避免的问题
闭包中使用 [weak self]循环引用
在 deinit 中调用 Timer.invalidate()Timer 泄漏
在 deinit 中移除观察者观察者泄漏
使用有限制的 NSCache缓存无限增长
图像降采样内存激增
使用 os_signpost 进行自定义性能分析
import os.signpost

let log = OSLog(subsystem: "com.app", category: .pointsOfInterest)

os_signpost(.begin, log: log, name: "DataProcessing")
// Expensive work
os_signpost(.end, log: log, name: "DataProcessing")
警示信号
问题特征问题修复方法
将索引用作 List ID修改时重建视图使用稳定标识符
body 计算开销大每次渲染都会运行移至 ViewModel
对传入对象使用 @StateObject创建新实例使用 @ObservedObject
Timer/闭包中强引用 self循环引用使用 [weak self]
缩略图使用全分辨率图像内存暴涨降采样至显示尺寸
无界字典缓存内存增长使用有容量限制的 NSCache
未使用 Task.detached 执行繁重工作阻塞主线程使用后台优先级

评论

支持 Markdown