Post marked as solved
Post marked as solved with 16 replies, 2,703 views
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
}
struct ContentView: View {
		@State var valueStruct: Double = 0.5
		@State var valueClass = VC()
		
		var body: some View {
				VStack {
						Text("STRUCT")
						Slider(value: $valueStruct)
						Text("\(self.valueStruct)")
						
						Text("")
						
						Text("CLASS")
						Slider(value: $valueClass.s1)
						Text("\(self.valueClass.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)