Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa constraints causing high cpu usage

I recently switched to NSLayoutConstraint in my app and I have suddenly noticed that, in some views, my app use about 20% or more of CPU constantly. As I said it only happens when some views are on screen and only after I switched to constraints.

By running the time profiler I noticed that [NSView displayIfNeeded] is called constantly in those views even though nothing happens, no events or user interactions. Also, if I resize my window I can find certain configuration where the CPU usage goes down to normal values. If I put back the window to its original size the CPU usage grows again and [NSView displayIfNeeded] gets called constantly again.

It seems like there are certain combinations of views and sizes that are refreshed constantly even though constraints are not crashing (no sign of unsatisfiable constraints error in the console).

Has anyone experienced this? Or at least knows how to track the problem better?

After a bit of try and error I have narrowed it down to this view Tableview cell

It's a custom cell in a TableView. If I replace it with a normal cell the cpu usage returns to normal. I have also checked that the layout is not ambiguous.

like image 675
Jacopo Avatar asked Aug 16 '12 23:08

Jacopo


1 Answers

This happens often because of rounding issues for constraints. Especially if you use "Equal Width" constraints.

Two Buttons with Equal Width Constraint

Another cause for a similar problem is using "Center in Container" constraints. Which often cause rounding problems.

Check your constraints if you used one of these constraints and lower the priority of them. This allows ignoring these rules if they don't fit well. Or even better, create the layout without center and equal width/height constraints.

like image 76
Flovdis Avatar answered Oct 05 '22 23:10

Flovdis