Communitygithub.com

ComeOnOliver/skillshub

當 UI 卡頓、捲動延遲、動畫不流暢時使用,或當你問『為什麼我的 SwiftUI 畫面這麼慢』、『如何最佳化 List 效能』、『我的 App 掉幀』、『View body 被呼叫太多次』、『List 很 lag』時使用 - 搭配 Instruments 26 和 WWDC 2025 模式的 SwiftUI 效能最佳化

skillshub 是什麼?

這項技能提供了一套全面的 SwiftUI 效能最佳化方法,特別是針對 iOS 26 和 WWDC 2025 中引入的新工具與模式。它詳細說明了如何使用全新的 SwiftUI Instrument (Instruments 26) 來診斷效能瓶頸,包括長時間的畫面更新和不必要的重新繪製。此技能不僅涵蓋了 iOS 26 框架層級的重大效能改進(例如 List 載入速度提升 6 倍、更新速度提升 16 倍),還提供了實際的程式碼範例和重構建議,例如避免在 View body 中建立昂貴的 Formatter,以及使用 Cause & Effect Graph 來追蹤資料流與狀態變更。支援平台包括 macOS、iOS、iPadOS 和 watchOS,主要適用於 Claude Code、Coder 等支援技能檔案的 AI 代理工具。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-swiftui-performance

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 效能最佳化

何時使用此技能

在以下情況使用:

  • App 反應不靈敏(卡頓、停滯、延遲捲動)
  • 動畫在執行過程中暫停或跳動
  • 捲動效能不佳
  • 效能剖析顯示 SwiftUI 是瓶頸
  • View body 執行時間過長
  • View 比必要頻率更頻繁更新
  • 需要了解 SwiftUI 更新的因果關係

範例提示詞

這些是開發者實際提出的問題,此技能旨在回答它們:

1. 「我的 App 有卡頓的捲動和動畫不流暢。如何判斷 SwiftUI 是否為原因?」

→ 該技能展示了如何使用 Instruments 26 中全新的 SwiftUI Instrument 來判斷 SwiftUI 是否為瓶頸,而非其他層。

2. 「我正在使用新的 SwiftUI Instrument,並看到橙色/紅色的長條表示長時間更新。如何知道是什麼造成的?」

→ 該技能涵蓋了因果關係圖 (Cause & Effect Graph) 模式,這些模式顯示了通過 App 的資料流,以及哪些狀態變更會觸發昂貴的更新。

3. 「有些 View 更新過於頻繁,即使它們的資料沒有改變。如何找到哪些 View 有問題?」

→ 該技能示範了不必要更新檢測,以及使用視覺化時間軸進行身份 (Identity) 故障排除。

4. 「我有大型的資料結構和複雜的 View 階層。如何針對 SwiftUI 效能進行最佳化?」

→ 該技能涵蓋了效能模式:分解 View 階層、最小化 body 複雜度,以及使用 @Sendable 最佳化檢查清單。

5. 「我們有一個效能截止期限,我需要了解 SwiftUI 中什麼地方慢。關鍵指標是什麼?」

→ 該技能提供了優先處理最佳化的決策樹,並理解壓力情境,以及針對權衡取捨的專業指導。


概述

核心原則:確保你的 View body 快速更新,並且只在必要時更新,以實現出色的 SwiftUI 效能。

WWDC 2025 新功能:Instruments 26 中的次世代 SwiftUI instrument 提供了全面的效能分析,包含:

  • 長時間更新的視覺化時間軸(按嚴重性以橙色/紅色標記)
  • 顯示 App 資料流的因果關係圖 (Cause & Effect Graph)
  • 與 Time Profiler 整合以進行 CPU 分析
  • 停滯與卡頓追蹤 (Hangs and Hitches tracking)

關鍵效能問題:

  1. 長時間的 View Body 更新 — View body 執行時間過長
  2. 不必要的 View 更新 — 資料並未實際變更時 View 卻更新

iOS 26 框架效能改進

「對框架的效能改進使 Apple 所有平台上的 App 受益,從我們的 App 到你的 App。」 — WWDC 2025-256

iOS 26 中的 SwiftUI 包含了主要的效能提升,所有 App 都能自動獲得。這些改進與新的剖析工具並行,使 SwiftUI 開箱即用更快。

List 效能(macOS 重點)

大型 List 的巨大提升

  • 載入速度提升 6 倍,適用於 macOS 上 100,000 個以上項目的 List
  • 更新速度提升 16 倍,適用於大型 List
  • 更大的 List 有更大的提升
  • 改進使所有平台受益(iOS、iPadOS、watchOS,不僅是 macOS)
List(trips) { trip in // 10萬+ 項目
    TripRow(trip: trip)
}
// iOS 26: 載入速度提升 6 倍,更新速度提升 16 倍(macOS)
// 所有平台皆受益於效能改進

對你 App 的影響

  • 大型資料集(1萬+ 項目)有顯著的改進
  • 過濾和排序操作完成得更快
  • List 的即時更新反應更靈敏
  • 對檔案瀏覽器、聯絡人列表、資料表格等 App 有益

捲動效能

減少高速捲動時的掉幀

SwiftUI 改善了 iOS 和 macOS 上 UI 更新的排程。這提高了反應速度,並讓 SwiftUI 能做更多工作來準備後續影格。總體而言,它減少了 App 在以高影格率快速捲動時掉幀的機會。

關鍵改進

  1. 更好的影格排程 — SwiftUI 有更多時間準備即將到來的影格
  2. 改善的反應速度 — UI 更新更有效地排程
  3. 更少的掉幀 — 特別是在 120Hz (ProMotion) 快速捲動時

你會注意到的時候

  • 捲動包含大量圖片的內容時
  • 高影格率裝置(iPhone Pro、配備 ProMotion 的 iPad Pro)
  • 具有多個 View 的複雜 List 行

帶有 Lazy Stack 的巢狀 ScrollView

圖片輪播和多軸捲動現在已正確最佳化

ScrollView(.horizontal) {
    LazyHStack {
        ForEach(photoSets) { photoSet in
            ScrollView(.vertical) {
                LazyVStack {
                    ForEach(photoSet.photos) { photo in
                        PhotoView(photo: photo)
                    }
                }
            }
        }
    }
}
// iOS 26: 巢狀的 ScrollView 現在能正確地延遲載入 lazy stack 內容
// 非常適合圖片輪播、Netflix 風格的佈局、多軸內容

在 iOS 26 之前 巢狀的 ScrollView 無法正確延遲載入 lazy stack 內容,導致所有巢狀內容立即載入。

在 iOS 26 之後 巢狀 ScrollView 內的 Lazy Stack 現在會延遲載入內容,直到內容即將出現,與單層 ScrollView 的行為相符。

使用情境

  • 帶有水平/垂直捲動的圖片庫
  • Netflix 風格的類別列
  • 多維度資料瀏覽器
  • 帶有垂直細節捲動的圖片輪播

SwiftUI 效能 Instrument 增強功能

Instruments 26 中的新通道

SwiftUI instrument 現在包含專用通道,用於:

  1. 長時間 View Body 更新 — 識別昂貴的 body 計算
  2. 平台 View 更新 — 追蹤 UIKit/AppKit 橋接效能(長時間 Representable 更新)
  3. 其他長時間更新 — 所有其他類型的長時間 SwiftUI 工作

這些通道將在下一節詳細介紹。

效能改進摘要

自動獲勝(僅需重新編譯)

  • ✅ List 載入速度提升 6 倍(10萬+ 項目,macOS)
  • ✅ List 更新速度提升 16 倍(macOS)
  • ✅ 減少捲動時的掉幀
  • ✅ 改善 iOS/macOS 上的影格排程
  • ✅ 巢狀 ScrollView 延遲載入最佳化

無需修改程式碼 — 使用 iOS 26 SDK 重新建置即可獲得這些改進。

交叉參考 SwiftUI 26 功能 (swiftui-26-ref skill) — 所有 iOS 26 SwiftUI 變更的完整指南


SwiftUI Instrument (Instruments 26)

開始使用

需求:

  • 安裝 Xcode 26
  • 將裝置更新到最新的 OS 版本(支援錄製 SwiftUI 軌跡)
  • 以 Release 模式建置 App 以進行準確的效能剖析

啟動:

  1. 在 Xcode 中開啟專案
  2. 按下 Command-I 進行效能剖析
  3. 從範本選擇器中選擇 SwiftUI 範本
  4. 點擊「錄製」按鈕

範本內容

SwiftUI 範本包含三個 instrument:

  1. SwiftUI Instrument (NEW) — 識別 SwiftUI 程式碼中的效能問題
  2. Time Profiler — 顯示隨時間變化的 CPU 工作樣本
  3. Hangs and Hitches — 追蹤 App 反應速度

SwiftUI Instrument 軌道通道

通道 1:更新群組 (Update Groups)

  • 顯示 SwiftUI 何時在積極進行工作
  • CPU 尖峰時為空? → 問題可能不在 SwiftUI 內

通道 2:長時間 View Body 更新 (Long View Body Updates)

  • 標示 body 屬性何時花費過長時間
  • 最常見的效能問題 — 從這裡開始

通道 3:長時間 Representable 更新 (Long Representable Updates)

  • 識別緩慢的 UIViewRepresentable/NSViewRepresentable 更新
  • UIKit/AppKit 整合效能

通道 4:其他長時間更新 (Other Long Updates)

  • 所有其他類型的長時間 SwiftUI 工作

顏色編碼系統

更新根據導致卡頓的可能性以橙色和紅色顯示:

  • 紅色 — 非常可能導致卡頓/停滯(優先調查)
  • 橙色 — 中等可能導致問題
  • 灰色 — 正常更新,無需擔心

注意:更新是否實際導致卡頓取決於裝置的狀況,但紅色更新的優先級最高。


理解 Render Loop

正常影格渲染

影格 1:
├─ 處理事件(觸碰、按鍵)
├─ 更新 UI(執行 view body)
│  └─ 在影格截止時間前完成 ✅
├─ 交接給系統
└─ 系統渲染 → 在畫面上顯示

影格 2:
├─ 處理事件
├─ 更新 UI
│  └─ 在影格截止時間前完成 ✅
├─ 交接給系統
└─ 系統渲染 → 在畫面上顯示

結果:流暢的動畫

帶有卡頓的影格(長時間 View Body)

影格 1:
├─ 處理事件
├─ 更新 UI
│  └─ 有一個 VIEW BODY 太慢
│  └─ 超過影格截止時間 ❌
├─ 錯過截止時間
└─ 前一個影格保持可見(卡頓)

影格 2: (延遲)
├─ 處理事件(延遲了 1 個影格)
├─ 更新 UI
├─ 交接給系統
└─ 系統渲染 → 終於可見

結果:前一個影格可見超過 2+ 個影格 = 動畫不流暢

帶有卡頓的影格(過多更新)

影格 1:
├─ 處理事件
├─ 更新 UI
│  ├─ 更新 1(快速)
│  ├─ 更新 2(快速)
│  ├─ 更新 3(快速)
│  ├─ ...(還有 100 個快速更新)
│  └─ 總時間超過截止時間 ❌
├─ 錯過截止時間
└─ 前一個影格保持可見(卡頓)

結果:許多小更新加起來導致錯過截止時間

關鍵見解:View body 執行時間很重要,因為錯過影格截止時間會導致卡頓,使動畫變得不流暢。

參考資料:


問題 1:長時間 View Body 更新

識別長時間更新

  1. 使用 SwiftUI 範本在 Instruments 中錄製軌跡
  2. 查看 Long View Body Updates 通道 — 有任何橙色/紅色的長條嗎?
  3. 展開 SwiftUI 軌道以查看子軌道
  4. 選擇 View Body Updates 子軌道
  5. 篩選長時間更新:
    • 詳細資訊面板 → 下拉選單 → 選擇 "Long View Body Updates summary"

使用 Time Profiler 分析

工作流程:

  1. 在 Long View Body Updates summary 中找到長時間更新
  2. 懸停在 View 名稱上 → 點擊箭頭 → "Show Updates"
  3. 右鍵點擊長時間更新 → "Set Inspection Range and Zoom"
  4. 切換到 Time Profiler instrument 軌道

你看到的內容:

  • 在 View body 執行期間記錄的樣本呼叫堆疊
  • 每個影格花費的時間(最左邊的欄位)
  • 你的 View body 嵌套在深的 SwiftUI 呼叫堆疊中

尋找瓶頸:

  1. Option-點擊以展開主執行緒呼叫堆疊
  2. Command-F 搜尋你的 View 名稱(例如 "LandmarkListItemView")
  3. 在時間欄位中識別昂貴的操作

常見的昂貴操作

格式化器建立(非常昂貴)

❌ WRONG - 在 View body 中建立格式化器:

struct LandmarkListItemView: View {
    let landmark: Landmark
    @State private var userLocation: CLLocation

    var distance: String {
        // ❌ 每次 body 執行時都建立格式化器
        let numberFormatter = NumberFormatter()
        numberFormatter.maximumFractionDigits = 1

        let measurementFormatter = MeasurementFormatter()
        measurementFormatter.numberFormatter = numberFormatter

        let meters = userLocation.distance(from: landmark.location)
        let measurement = Measurement(value: meters, unit: UnitLength.meters)
        return measurementFormatter.string(from: measurement)
    }

    var body: some View {
        HStack {
            Text(landmark.name)
            Text(distance) // 呼叫昂貴的 distance 屬性
        }
    }
}

為什麼慢:

  • 格式化器建立起來很昂貴(每個數毫秒)
  • 每次 View body 執行時都建立
  • 在主執行緒上執行 → App 在繼續 UI 更新前等待
  • 多個 View → 時間很快累積

✅ CORRECT - 集中快取格式化器:

@Observable
class LocationFinder {
    private let formatter: MeasurementFormatter
    private let landmarks: [Landmark]
    private var distanceCache: [Landmark.ID: String] = [:]

    init(landmarks: [Landmark]) {
        self.landmarks = landmarks

        // 在初始化期間只建立一次格式化器
        let numberFormatter = NumberFormatter()
        numberFormatter.maximumFractionDigits = 1

        self.formatter = MeasurementFormatter()
        self.formatter.numberFormatter = numberFormatter

        updateDistances()
    }

    func didUpdateLocations(_ locations: [CLLocation]) {
        guard let location = locations.last else { return }
        updateDistances(from: location)
    }

    private func updateDistances(from location: CLLocation? = nil) {
        guard let location else { return }

        for landmark in landmarks {
            let meters = location.distance(from: landmark.location)
            let measurement = Measurement(value: meters, unit: UnitLength.meters)
            distanceCache[landmark.id] = formatter.string(from: measurement)
        }
    }

    func distanceString(for landmarkID: Landmark.ID) -> String {
        distanceCache[landmarkID] ?? "Unknown"
    }
}

struct LandmarkListItemView: View {
    let landmark: Landmark
    @Environment(LocationFinder.self) private var locationFinder

    var body: some View {
        HStack {
            Text(landmark.name)
            Text(locationFinder.distanceString(for: landmark.id)) // ✅ 快速查詢
        }
    }
}

好處:

  • 格式化器只建立一次,為所有地標重複使用
  • 當位置變更時預先計算字串
  • View body 僅讀取快取值(即時)
  • 消除了長時間的 View body 更新

其他昂貴操作

複雜計算:

// ❌ 不要在 View body 中計算
var body: some View {
    let result = expensiveAlgorithm(data) // 複雜數學、排序等
    Text("\(result)")
}

// ✅ 在模型中計算,快取結果
@Observable
class ViewModel {
    private(set) var result: Int = 0

    func updateData(_ data: [Int]) {
        result = expensiveAlgorithm(data) // 只計算一次
    }
}

網路/檔案 I/O:

// ❌ 絕對不要在 View body 中進行 I/O
var body: some View {
    let data = try? Data(contentsOf: fileURL) // ❌ 同步 I/O
    // ...
}

// ✅ 非同步載入

(由於內容已截斷,翻譯至此結束)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能