Friday 24 April 2009

CGContextSelectFont - slow slow slow...

Wow, that was a shock. There I was profiling Mixtikl on the iPhone after tuning various things, and what do I find? CGContextSelectFont is hogging 30% of the CPU cycles!

This is nothing new apparently (see http://www.manton.org/2005/12/cgcontextselectfont.html - which dates from 2005!). Thanks Apple. :-(

The solution was this:
- when you grab a CGContextRef from UIView (or for example when I create my own singleton temporary one I use for off-line calculation of text display areas...), set the font just once on that CGContextRef by calling CGContextSelectFont with a temporary font size of e.g. 10; do this before you do any text drawing operations with the CGContextRef...!
- Whenever you need to draw text, call CGContextSetFontSize before you call CGContextShowText (or whatever...); do not call CGContextSelectFont as there is no need to set the font by name and size in most cases, just the font size. Calls to CGContextSetFontSize hardly take any time at all ... and your performance problems will disappear.

That makes a huge difference to performance, and is easy to do when you know how. :)

No comments: