Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Xamarin

Reconsider Overriding UIView.Draw or UIView.DrawRect

4.63/5 (8 votes)
31 Oct 2014CPOL2 min read 21.3K  
There is a very high virtual memory penalty if you do.

Introduction

I didn't think I was asking much. I wanted a UIView that could have a different (or no) border on each side.

Background

This problem has been haunting me for about two months. I am creating an Outlook-style calendar component for iOS. If you consider such a control, you'll realize it is made up of hundreds of child controls:

Image 1

In fact, the grid alone in week view requires 7 days × 24 hours × 4 divisions per hour = 672 views.

After a couple of weeks, I concluded that I needed to dump iOS's AutoLayout feature in favour of writing my own alternative. Its algorithms are way too slow to handle that number of views, and it would take up to 10 seconds or more to build and render the calendar.

After all memory leaks were taken care of, there remained a new problem. Even though memory on the heap was being freed, there remained a huge allocation of virtual memory (114MB shown):

Image 2

After weeks of searching for a solution, I read a comment that said that the 2012 WWDC session 242: iOS App Performance: Memory by Morgan Grainger was useful. In that presentation, Morgan referenced another session, #238 iOS App Performance: Graphics and Animations. About 2/3 through this session, the presenter mentions that overriding DrawRect comes with a high VM penalty. Even if your override looks like:

C#
override void DrawRect(RectangleF rect)
{
}

The OS will allocate VM for drawing. The reason I was user-drawing is that iOS does not provide a way to draw borders in which the sides of the border are different colour or width. I was drawing these manually using CoreGraphics.

The Solution

As an experiment, I tried doing it the ugly way: I drew 4 rectangles, each one a subview, each with a length equal to a side and a width equal to the border width. The difference in VM usage is astonishing:

Image 3

It doesn't even register.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)