Hey guys just a quick question about the performance of drawRect: as I’ve noticed a lot of topics with people complaining about performance issues.
In my App, I need to draw ~150 squares overtop some underlaying views. Obviously this many calls isn’t going to have a noticeable user difference, but I’m just wondering about the pros and cons going forward. Currently I’m debating two ways:
1) add a transparent UIView subclass on top with a custom drawRect: to facilitate the drawing
2) just add normal square subviews
As I said, using CADisplayLink there won’t be any difference to the user, I’m just curious what would be more efficient? (2) is kind of a ridiculous way of doing it, adding instances with useless functionality just for appearance, but all these posts have just scared me into using drawRect. Is drawRect really that inefficient?
Thanks
Perhaps unintuitively,
drawRect:isn’t called for every frame. In fact, if you do nothing special in your view and your view itself doesn’t change, it gets called once.You can force it to be called by calling
[myView setNeedsDisplay], but there usually is no reason to.If you have a view with overlapping subviews, still for each of those views, including the superview,
drawRect:is only called once. Then, the GPU does the compositing (blending).A custom
drawRect:is almost always slower (and harder) than just using UIKit the way it was intended, if UIKit already offers what you want to do.Also don’t fall into one of the biggest traps in software development, premature optimization. Code the most naive version, benchmark it, and if it’s fast enough, it’s good enough, and you can focus your energy elsewhere. Only start optimizing once you know that something is actually slow, and where and why it is.