3

I'm building a UIView with a custom drawRect function. This is a fairly complex view, with a number of different items that need to be drawn. I've basically broken it down into one function per item that needs to be drawn.

What I'm wondering is should I pass my CGContextRef, obtained from UIGraphicsGetCurrentContext(), as a parameter to each function, or can I just call it at the start of each function? The latter option looks neater to me, but I am wondering if there is much of a performance penalty?

Ben Williams
  • 4,695
  • 9
  • 47
  • 72

3 Answers3

4

It's the same, unless you are saving/restoring context all around. In any way, getting the context from that method will, most probably, never be the bottleneck.

I suggest that if you are not saving and restoring states, you could use the UIGraphicsGetCurrentContext(). However, if you are indeed saving state, you should pass this one since it would be easier to read your code.

It's a matter of style I guess...

Pier-Olivier Thibault
  • 3,907
  • 2
  • 33
  • 33
3

Pier-Olivier's response is good, and just grazes the key issue: don't worry about it until you have to. This is a case of premature optimization. Before spending a lot of time deciding whether to pass around your CGContextRef, you should write your application and then look at the performance. Using Instruments can help you figure out where your real bottlenecks are. If it turns out this is causing problems (which I highly doubt), then you can optimize it.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Fair enough, but what makes you assume I'm not worrying about it because I have to? Having some knowledge of how to avoid certain bottlenecks in the first place rather than spending time identifying them in Instruments is a better way to go, in my opinion. – Ben Williams May 24 '11 at 04:43
0

just profile after it's implemented correctly and well tested.

if it really shows up as a hotspot, then your problem is likely best divided, and/or rendered to an offscreen context... or by using lower level rendering.

justin
  • 104,054
  • 14
  • 179
  • 226