ios - Is drawing rounded corner in drawRect: faster than using CALayer setCornerRadius? -


in 2011's wwdc video session 121, improve performance of ui, presenter chose draw rounded corners using uibezierpath in drawrect:, rather setting corner radius directly on layer.

why drawing using uibezierpath faster? drawrect: happens in software can slow too.

short answer: stick calayer’s cornerradius until see performance problem.

long answer:

we first need distinguish between “drawing” , “compositing”.

drawing on ios simple act of filling texture pixels (a cpu limited task). compositing act of flattening of textures single frame print screen (a gpu limited task). speaking, when scrolling or animating you’re taxing gpu, cause things shifting pixels down 1 gpu eats breakfast.

-drawrect: pure drawing, , uses cpu fill texture. calayer’s cornerradius done @ compositing step, , stresses gpu.

using -drawrect: has high initial cost (it take longer 1 frame) , non-trivial memory usage, scrolls smoothly after (it’s texture other texture). using calayer’s corner radius ridiculously fast create bunch of views corner radius, once more dozen of them can goodbye scrolling speed (because gpu not has normal scrolling duties needs keep adding corner radius onto view).

but don’t take word it, have math. adapted florian kugler’s benchmark , ran on iphone 4s running ios 6.1.3. measure how many views can created in 1/60th of second, measure how many views can animated before frame rate drops below 60fps. in other words: upfront cost vs framerate cost.

                                         | -drawrect:     | calayer’s cornerradus max number of views rendered in 16.6ms  |     5 views    |     110 views max number of views animating @ 60fps  |    ~400 views  |     12 views 

(note app killed using memory @ 500 -drawrect: views)

at end of day, in own projects tend stick calayer’s cornerradius as possible. i’ve needed more couple of views round corners , -drawrect: has of initial performance hit. , subclassing view round corners just, ugh.

but no matter method end choosing, make sure measure , pay attention how smooth , responsive app is, , respond accordingly.


Comments