Menu

CGContextSelectFont is slow

We’ve heard it countless times: Before you spend any time optimizing, profile your code. And yet we always think we know where the performance problems are without testing.

Earlier this year I started some extra work to help a company port their Windows software to the Mac. It turned into a large project, and when the app ships I will write more about it here. But for now let’s just say that it involves a lot of Windows bitmaps.

Performance had been a problem almost from the start. It is a very drawing-intensive application, and I spent time optimizing the path to Quartz. Eventually everything goes through a CGImage, but there is some overhead getting there. I knew more could be done.

Eventually I bothered to run Shark on it. Within 30 seconds it revealed that almost 50% of the application time was being spent inside CGContextSelectFont, which was called very frequently for the very basic text drawing that was needed. I had not even suspected that code. I rewrote it to use ATSUI and all the performance problems immediately melted away. And it wasn’t even optimized ATSUI — just brain-dead create a text layout, font size, and draw.

It was not obvious to me that CGContextSelectFont would be so slow, so I’m posting this one for Google to pick up. Happy coding!