swiftxcodeswiftuiswiftui-previews

Better Performance in SwiftUI: Creating a new view OR using a function with @ViewBuilder


When working with different view composition in SwiftUI, we can take two approaches:

  1. To use some @ViewBuilder function inside the view as a helper function:
@ViewBuilder func makeButtonLabel() -> some View {
    if isPlaying {
        PauseIcon()
    } else {
        PlayIcon()
    }
}
  1. To create a different view for that UI piece:
struct SongRow: View {
    var song: Song
    @Binding var isPlaying: Bool
    ...

    var body: some View {
        HStack {
            if isPlaying {
                PauseIcon()
            } else {
                PlayIcon()
            }
        }
    }
}

I wonder which one is better and how we can measure it?

Analytically, it seems to me the second one has better performance in bigger view chunks, especially we can see it in the preview's loading time, but I don't have any clue for it.


Solution

  • You can assume performance difference is negligible, if any. structs are very light weight - go for the one which makes most sense in your context. Also, you don't need that HStack in the 2nd example, since body is implicitly a @ViewBuilder.

    In the end, neither of these are better than the other since there is no measurable affect.

    Typically, I prefer to split views which are getting large or would make more sense to be its own view. For example: