问题
I am trying to get the maximum performance out of SwiftUI. I have a complex view and a lot of state and not sure what penalties I am paying as I calculate a lot of views programatically.
The view is something like this, stripped to the bare minimum
struct ComplexView : View {
@State var a = 1
@State var b = 2
// .. more state
// Perform function and change some of the state
func doIt ( index : Int ) {
// ... change some state
}
// Calculate some view based on state and index
func calcView ( index : Int ) -> some View {
// Debug
print ( "Generating view for index \( index )" )
// e.g. based on state and index and also use doIt function
// note this requires access to this struct's functionality
return Button ( action : { self.doIt ( index : index ) },
label : // ... complex calc based on index and maybe on state
)
}
var body : some View {
// ... lots of complex views based on state
DirtyA
DirtyB
// ... lots of complex views NOT based on state
CleanA
CleanB
// ... lots of calculated views that are based on state
calcView( index : 1 ) // dirty
calcView( index : 2 ) // dirty
// ... lots of calculated views that are NOT based on state
calcView( index : 101 ) // clean
calcView( index : 102 ) // clean
}
}
My question really is how to do the body for maximum performance. At present it seems everything gets rerendered everytime state changes. How do I prevent that?
Should I put all 'dirty' views in their own struct bound to state so that only they are rerendered?
Should I put all 'clean' views in their own struct to prevent those from rerendering?
SwiftUI is supposed to be clever enough to render only changes - can I safely trust this?
That is the easy part, how about the calculated ones? How do I ensure the dirty ones are rerendered when state changes without rerendering the clean ones?
FWIW the one debug line in the code above that prints when a view is calculated is what leads me to this question. It prints everytime and for all indices when state changes, so I think there is a lot of unnecessary rendering taking place especially for the calculated views. However, if SwiftUI is clever enough to only rerender changes, then I need not worry and need not change my approach.
来源:https://stackoverflow.com/questions/65536210/complex-swiftui-view-performance