Question

While drawing view background what is the best practice to follow? using NSColor and NSRectfill or using Core Foundation objects like CGColorRef and CGContextSetFillColorWithColor? is there any performance benefits when you use Core foundation Objects?

Was it helpful?

Solution

The factors to consider

Ease of use

The AppKit drawing APIs, including NSRectFill, are generally easier, since there's less to pass around. It's also way easier to create NSColors than CGColors (outside of white and black).

Thread-safety

Since you don't pass in a context with AppKit APIs (all drawing goes to the current context), there's no way to safely do AppKit drawing on any thread but the main thread.

You shouldn't do CG drawing with an AppKit-originated context, either. If you want to draw on another thread, create your own context, capture an image from it afterward, and throw it back to the main thread using dispatch or a main-thread perform.

Performance benefits

Assume zero.

The expensive part of drawing is drawing. Shadows are biggest, followed by rasterizing paths (including, especially, text). Compositing of rasters (e.g., CGImages and NSBIRs) is faster than you might expect.

Switching from NS* drawing APIs to CG* is microscopic by comparison. Spend your optimization time elsewhere, as directed by your findings in Instruments.

About the only place where such a change might be worth it is (unsurprisingly) text: Core Text can be a small but measurable amount faster than AppKit text drawing. The optimal case with either one is an unchanging string that you can keep around and reuse: in the case of Core Text, you'd keep the framesetter and/or frames; with AppKit drawing, you can only keep the attributed string. If your string is changing frequently, there is nothing for it: drawing it is just going to be expensive either way. But, again, profile first and don't worry about this until you've proven that it's significant in your app.

Portability

CG code can be used on both Mac and iOS with little to no modification. AppKit drawing code only works where AppKit exists: on the Mac.

Verdict

Use AppKit drawing, unless you want to port to iOS (or maintain an existing iOS version), in which case, use Core Graphics and reuse as much drawing code as you can on both.

(Assuming, of course, that the code draws the same thing on both platforms. If it draws differently on each, it should just be two separate lumps of code, in which case each one can use platform-specific APIs, since each one is platform-specific anyway.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top