问题
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?
回答1:
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...
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/6104736/is-there-any-performance-loss-when-repeatedly-calling-uigraphicsgetcurrentcontex