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

2

11

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.

Cloris answered 10/8, 2021 at 16:43 Comment(0)
G
7

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.

Gloam answered 10/8, 2021 at 17:25 Comment(5)
Apple has been pretty clear there is no real performance hit either way. It is all in how you want to organize your code.Sherrell
@Sherrell Thank you, in which Apple documentation it's mentioned?Cloris
They emphasized it at WWDC. it is in a bunch of the videos. when it gets compiled, it all gets flattened into one view, so no penaltiesSherrell
@ViewBuilder var buttonLabel: some View And new struct, which one is better for performance?Scissure
@BinhHo Computed property vs a function is going to make no difference, therefore computed property vs a struct is already answered. Stop focusing on such micro-optimisations.Gloam
U
-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.

Unshod answered 2/8, 2022 at 23:2 Comment(1)
Do you have a source for that?Cholecyst

© 2022 - 2024 — McMap. All rights reserved.