Complex SwiftUI view performance

被刻印的时光 ゝ 提交于 2021-02-11 12:20:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!