skip to Main Content

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.

2

Answers


  1. 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:

    • If you have a component of a view which heavily relies on properties in the current struct instance, you can create a new @ViewBuilder var buttonLabel: some View/@ViewBuilder func makeButtonLabel() -> some View and easily access the same properties.

    • If the properties are unrelated, split it into a separate view. Doing this also makes it easier to reuse across the app, and run in SwiftUI previews.

    Login or Signup to reply.
  2. From the performance side, never use the function to create views since it does not cache.

    Yes, it makes little difference for small applications but matters big if you are working on a complicated one.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search