NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Why is a Class faster in SwiftUI than a Struct? (with example)

Forums > SwiftUI

Hi all,

can someone more experienced or smarter than me please take a look at this example code?

I was struggling with performance issues using SwiftUI with an MTKView and found out that the Struct I was using to keep the bindings was the guilty one. After hours of searching and trying stuff, I found out that using a Class solved the performance issues. It introduces other issues though, like the UI not always updating everywhere, and all my sliders returning to zero when my macOS app window is minimised or has no focus.

Even though I understand the difference between value and reference types, and that copying a Struct each time takes CPU cycles, I don't understand why my Class values seem to be unreachable at times by the UI...

Here's the macOS example code:

//
//  ContentView.swift
//  SlowStructFastClass
//
//  Created by Michel Storms on 12/01/2021.
//

import SwiftUI

class VC {
    var s1: Double = 0.5
}

class VD: ObservableObject {
    @Published var s1: Double = 0.5
}

struct ContentView: View {
    @State var valueStruct: Double = 0.5
    @State var valueClass = VC()
    @ObservedObject var valueClassObserved = VD()

    var body: some View {
        VStack {
            Text("STRUCT")
            Slider(value: $valueStruct)
            Text("\(self.valueStruct)")

            Text("CLASS")
            Slider(value: $valueClass.s1)
            Text("\(self.valueClass.s1)")

            Text("CLASS - OBSERVABLEOBJECT")
            Slider(value: $valueClassObserved.s1)
            Text("\(self.valueClassObserved.s1)")
        }
    }
}

I think this is the simplest I could make the example, yet there is still a big speed difference between struct and class binding-based sliders...

Any clues? What am I doing wrong?

Thanks for your time!

(tested on a 2020 i5 MBP running Big Sur)

edit: I added a case where I use ObservableObject / ObservedObject as suggested by Raja Kishan. This improves the responsiveness of the UI, but is still noticeable slower than the Class example.

   

I see no difference whatsoever between the struct-based slider and the class-based.

What I do see is that you should not be using @State with a reference type, which you do here: @State var valueClass = VC(). @State is for value types.

I don't understand what you mean by this: "I don't understand why my Class values seem to be unreachable at times by the UI"

I also see that you are using an MTKView. Perhaps SwiftUI is interfering with the Metal rendering, as per this SO thread: SwiftUI updates reduce FPS of metal window?

   

Hi,

there is a big difference though, but only on macOS... weirdly enough doing the same thing in an iOS emulator shows 3 sliders that behave the same.

The MTKView works perfectly, I get a solid 60fps when using the Class-based bindings, and about 6 when using the struct based ones. I understand that using a reference type as an @State is not ideal, but for now it is the only way I get decent sliders.

What I mean by the UI thing is a direct consequence of this, sadly. I mean that SwiftUI does not always update the view to whe binding. You can see this in my example, the Class based slider does not update its value text field...

I spent one of my 2 yearly code-level helps to get help from an Apple Engineer, something's definitely off or I am doing something very wrong here.

Will update here when I got news from them.

   

I see no appreciable difference on macOS:

slow struct, fast class

What I mean by the UI thing is a direct consequence of this, sadly. I mean that SwiftUI does not always update the view to whe binding. You can see this in my example, the Class based slider does not update its value text field...

Using @State with a reference type is the cause of this. If you'll notice in my GIF, the text field connected to the middle slider doesn't update after sliding until you touch one of the other sliders. Because it uses @State with a reference type, which doesn't work to keep the values in synch; it will only update once either the @State used with a value type (i.e., the first slider) or the @ObservedObject used with a reference type (i.e., the third slider) changes.

   

Yes I totally agree on the value / reference thing.

Thanks for taking the time for making that GIF. It does show the differemce though. The "class / middle" slider clearly sticks to the poinrer, where the others lag a bit behind. That lag gets way worse on an array of a few more sliders...

Its probably a result of the way SwiftUI works, Im just curious what Apple has to say about this and what they will offer as a workaround.

For those interested, here are 3 videos to compare the performance:

https://www.icloud.com/iclouddrive/0m2o4VTzRyD12IkKj0BJptIqg#Class_vs_Struct

This is literally on the same code, only the binding was chenged.

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.

Try the book!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.