This appendix is a reference for keeping shader effects fast and cheap on battery: picking quality by device and device state, estimating memory, finding bottlenecks with Apple's tools, and a list of optimizations in rough order of payoff. GPU costs vary between chip generations and depend on the whole frame, so this appendix avoids fixed cycle counts. Measure on the devices you support.
GPU families
SwiftUI's shader modifiers need iOS 17 or later, so every device that runs your shaders has a reasonably modern GPU. There is still a big gap between the oldest and newest of them. Metal groups GPUs into families (.apple7, .apple8, and so on, with higher numbers for newer GPUs). Apple's Metal feature set tables list which chips belong to each family.
You can ask the device which families it supports and bucket devices into tiers:
enum GPUTier {
case baseline // Older than Apple 7
case mid // Apple 7
case high // Apple 8 and newer
static func current() -> GPUTier {
guard let device = MTLCreateSystemDefaultDevice() else { return .baseline }
if device.supportsFamily(.apple8) {
return .high
} else if device.supportsFamily(.apple7) {
return .mid
} else {
return .baseline
}
}
}
What each tier gets (sample counts, loop iterations, which effects are on) is your call. Set it by profiling on the slowest device you support. The ShaderQuality enum in Appendix A shows one way to hold those settings. The device's current state matters as much as its family: a hot or battery-saving phone should drop quality whatever its tier.
Battery and heat
Measuring
There is no public API that reports how much power your app draws, so a shader can't measure its own cost at runtime. Measure during development instead:
- Xcode's Energy Impact gauge in the Debug navigator gives a quick relative reading while the app runs.
- The Power Profiler instrument in Instruments shows power use by subsystem (CPU, GPU, display, networking) over time. It can also record a trace on the device away from Xcode.
Compare the same screen with the effect on and off. The difference is what the effect costs.
Reacting at runtime
What the app can read is the system's response to load. ProcessInfo.processInfo.thermalState goes from .nominal through .fair and .serious to .critical as the device heats up, and isLowPowerModeEnabled tells you the user asked to save battery. A continuously animated shader is one of the easier things to scale back:
struct ShaderConfiguration {
var framesPerSecond: Double
var quality: ShaderQuality
static func current() -> ShaderConfiguration {
let info = ProcessInfo.processInfo
if info.isLowPowerModeEnabled {
return ShaderConfiguration(framesPerSecond: 30, quality: .low)
}
switch info.thermalState {
case .nominal:
return ShaderConfiguration(framesPerSecond: 60, quality: .high)
case .fair:
return ShaderConfiguration(framesPerSecond: 30, quality: .medium)
case .serious:
return ShaderConfiguration(framesPerSecond: 30, quality: .low)
case .critical:
return ShaderConfiguration(framesPerSecond: 15, quality: .low)
@unknown default:
return ShaderConfiguration(framesPerSecond: 30, quality: .medium)
}
}
}
Apply the frame rate through the TimelineView that drives the animation:
TimelineView(.animation(minimumInterval: 1.0 / config.framesPerSecond)) { timeline in
// ...
}
Listen for ProcessInfo.thermalStateDidChangeNotification and .NSProcessInfoPowerStateDidChange to recompute the configuration when either changes. Also stop the timeline entirely when the view is off screen: TimelineView(.animation(paused: true)) does nothing until you unpause it.
Memory
Offscreen layers
colorEffect only needs the current pixel's color. layerEffect and distortionEffect read other pixels, so SwiftUI first renders the view into an offscreen texture, then runs the shader on that. The texture is in pixels, not points.
A worked example: a full-screen layer effect on a phone with a 393 × 852 point screen at 3x scale renders a texture of 1179 × 2556 = 3,013,524 pixels. At 4 bytes per pixel (8-bit RGBA) that is about 12 MB, and more if SwiftUI uses a higher-precision format. The same effect on a 300 × 200 point card at 3x is 900 × 600 pixels, about 2 MB. Apply layer effects to the smallest view that needs them.
Inside the shader
Each pixel's variables live in registers, and the GPU has a fixed number of them. A shader that keeps many values alive at once lets the GPU work on fewer pixels in parallel. Accumulating as you go keeps register use low:
// Holds 16 colors in registers at once, then combines them in a second loop
half4 colors[16];
for (int i = 0; i < 16; i++) {
colors[i] = layer.sample(position + offsets[i]);
}
// Keeps one running total instead
half4 result = half4(0);
for (int i = 0; i < 16; i++) {
result += layer.sample(position + offsets[i]) * half(weights[i]);
}
Here offsets and weights are small constant arrays at file scope. A table of a few dozen weights is cheap. Precomputing weights there is usually better than calling exp() for every tap of every pixel, but measure if it matters.
Profiling tools
Instruments
- Metal System Trace: a timeline of GPU work per frame. Use it to check whether GPU time fits inside the frame budget (about 16.7 ms at 60 Hz, 8.3 ms at 120 Hz).
- Animation Hitches: shows frames that missed their deadline, and whether the app or the render side was late.
- SwiftUI: shows view body updates. A shader argument that changes every frame re-renders its view every frame, so check that only the views you expect are updating.
- Power Profiler: energy use over time, as above.
Profile on a device, in a Release build. The Simulator renders on the Mac's GPU, and Debug builds add overhead on the CPU side.
Frame capture
Xcode's Metal frame capture (the Capture GPU Workload button in the debug bar) records every GPU command in a frame and lets you step through them. It's most useful when your app drives Metal itself, for example with an MTKView. For SwiftUI shader effects, start with Instruments.
Optimization quick reference
Relative costs
Without fixed numbers, a rough ordering from cheap to expensive:
- Add, subtract, multiply, and fused multiply-add (
a * b + c): the cheapest operations. - Divide,
sqrt,rsqrt,length,normalize: more expensive than a multiply. If you divide by the same value many times, compute1.0 / xonce and multiply. sin,cos,exp,pow,log: more expensive again. Replacepow(x, 2.0)withx * x.layer.sample()and texture reads: memory accesses. Their cost depends on whether the data is already in cache, and nearby pixels reading nearby locations is the cache-friendly case.
Precision
half is a 16-bit float. It's enough for colors, which only need values between 0 and 1. It's risky for positions and time, because its precision drops as values grow:
- Between 256 and 512,
halfcan only step by 0.25. A position of 300.1 points rounds to 300.0. Past 512 the step is 0.5, and past 1024 it's a whole point, which shows up as stair-stepping in fine patterns and gradients on larger views. - Between 2048 and 4096, it steps by 2. A time value stored as
halfafter 34 minutes moves in two-second jumps.
Keep positions, sizes and time in float, and use half for color math.
Optimization priorities
- Reduce samples. Fewer
layer.sample()calls per pixel is usually the biggest win. - Shrink the area. A smaller view means fewer pixels running the shader, and a smaller offscreen layer for layer effects.
- Lower the frame rate or pause. A shader that doesn't need 120 updates per second shouldn't get them.
- Avoid divergent branches. Branching on a uniform argument (the same for every pixel) is fine. Branching on per-pixel values can make a group of pixels run both sides of the
if. - Use
halffor colors,floatfor positions and time. - Reuse calculations. Compute a value once and keep it, rather than recomputing it in each loop iteration.
- Keep loop bounds fixed where possible. A loop with a constant count is easier for the compiler to unroll.
- Approximate expensive functions when the result only needs to look right, such as a polynomial in place of
sinfor a wobble.