Search code examples
iosswiftperformance-testing

should i use CAlayer for shadows or should i use images


i want to ask that what is more costlier for iphone to render. a button given shadow with CALayer or button with image. now i know one button would not make any difference but what about if i have 10k records in uitableview.


Solution

  • CALayer for shadows

    I guess you are referring to the default way to creating shadows like the following by saying CALayer for shadows

    layer.shadowColor = 
    layer.shadowOffset =
    layer.shadowOpacity =
    layer.shadowRadius =   
    

    Preparing the shadow this way is computationally expensive, since GPU needs dynamically calculate overall color and opacity of for the part of the visible screen where shadow is to be applied.

    Since you are going to use this shadow in a scroll view, this calculation is to be done within 17ms to maintain a standard 60Hz refresh rate. Keep in mind that in this time you also need to made some side calculation for

    1. extracting the data model from large array.
    2. calculate other cell attributes (in case of sub-classing UICollectionViewLayout).

    My suggestion will be to use

    1. shadow path
    2. use an image from asset catalog for dropping a fixed size shadow
    3. pre-render your shadow into an image and cache it to use later as a shadow.

    Otherwise Debug-View may show you some warning like the following enter image description here

    Optimization Opportunities: The layer is using dynamic shadows which are expensive to render. If possible try setting shadowPath, or pre-rendering the shadow into an image and putting it under the layer.

    You will find more instruction from this tutorial.