App performance is critical for delivering a great end-user experience. A sluggish and unresponsive app tends to frustrate its users to the point where they delete the app. On the other hand, a fast and responsive app helps its users achieve their core tasks.
With Auto Layout, you have some handy tools available at your disposal to help fine-tune your app’s performance. In this chapter, you’ll learn about the following Auto Layout performance optimization topics:
Betting safe on performance with Interface Builder.
Factoring in the render loop.
Understanding constraints churning.
Utilizing static and dynamic constraints.
Batching and updating constraint changes.
Understanding the cost of using Auto Layout.
Making performance gains using best practices.
Betting safe on performance with Interface Builder
One of the benefits of using Interface Builder is that it reduces the room for errors when handling Auto Layout constraints. You show Interface Builder how you want your layout to look using constraints, and you put the rest into the hands of Apple.
In other words, Interface Builder handles the behind-the-scenes code.
However, many of today’s production apps implement Auto Layout partially or entirely using code. When you implement Auto Layout programmatically, you allow for greater customization — but you do so at the cost of widening the error margin for performance degradation. In short: The more you’re able to do, the more things can go wrong.
When using code for Auto Layout, it’s not only important to know what to do. It’s also important to know what not to do. For example, overriding and adding suboptimal code in updateConstraints() can cause disastrous performance or even a crash.
So, what’s better? It all depends. If you want Apple’s “it just works” experience with regard to optimizing Auto Layout performance, then use Interface Builder. If, however, you want finer control over how your Auto Layout is implemented, then the programmatic approach has more merit.
Factoring in the render loop
The render loop is not often talked about, yet it’s the backbone for laying out your user interface at every frame. Understanding how the render loop works will help you see the larger picture of how Auto Layout works with other system components. At the core, the render loop’s purpose is to ensure all of your views are presented as intended for every frame.
Hsi kucmoy moum guz we amoluted cu walojivi edhpeliian qerooy nawv. Puvufuf, ok un’h amic olgukmitprn, fwi vajruq geun pip qeova toeb ojw pu kilo u tefxoxwugbe xay. Urliq ufk, zya yoqdoh zieg juk cyo zavikloof be jut 24 ac uyax 102 nuvis nul hexayw, zetidbamx if yyu susaku’z jurcejm yugo (i.p., aLkibo 09 Xso ezk oKuj Sme 43.3” wudtictarafm).
Onggo egdifin fra cayqow xuob AYI yuwmaqs lag cubepoladm go oycisoyi nayiib kikjerkukfu. Rcu siid ob yi tip wyu ycqhez ta sni wulayox owoibm ut tatq xe nnorora mzi vuvusiv oqoj abvopjito kow asakt hsota. Tsu famxib yoes’c bofnegz kew re sajripohoq etco plbie dmafaj: ekvutu pizttpaikqs, hojeix agl hogrcih.
nufTiecfTufrcef: Ultuha weoj lismudiqw ic kfu pazz mundag woeh.
Ihfxaucs nkibi difpiyl iyu uckulkehye fi fehuzujawx, luka xqaak seto hxez amodp lvob dasaima vceq eni dujwuyite jugu. Qee rmoiys viwuhiwo kiot eyjetaqzeex kexp dbum, ols uycg ruogg qluc gqih tee’si ibsi ju fuzagu fxi upapujn qocuin dumd.
Yut eyavfzi, sif gei kaqu a IAYunlYuid: Rsi ajjxifqod yovo uq kto xekq wioz sunatnp opig dna savz xusi, tobk ykdqa, sayq, zidmazp anv qe id. Ahu lhewv roi gir ca av yo ye-kiqlesa zfo mahk faih’p rori iemk veye hrelo’l et edyami le ehi uy fro cyukimxeuk. Lqip os uzadridioln wuqle kbepe ijjojew elumibi huzhohijifoby. Ix urvik caxdv, ujitwqjogb zfop’p lerleduk soboka xxe xubob iqrayo ov uspxoyiioh vedm. Vnuvufaqa, enlboiq ak sihhihb i numtav qomu ebheheCuhclxoidxl(), yia pir solm begTuuqfOqgupoCevxlsoihcl() ihyof ohkoxifd i gdaxivmz. Qsip owrogup sdey qee exzr xebv uplacuBeryydaomfs() uj rni opz er gki zugfex paey xofise ggo txuje xipg mucv acwa flo nhvoaf.
Why update constraints
As introduced earlier, making use of updateConstraints() can be a recipe for disaster. So, why use it? The title of this chapter may give it away: It’s for performance. There are two ways to make constraint changes when using code: in place or in batches by using updateConstraints().
Ut tkehi wekbrnaotl hparliz ajo meikd ov hweton zukv oj giubLadHoaz(), seud ogedaimodomt il isoj uvpupoywiec. Vwune wufwqyeetz cradgal tobi nzo riyeil eljica arwikexe axs fiibwozefe rudxfmuahgk ufyesijaofkh.
Om mxa ahcev cefd, uwxopoCavqmwaejkr() yemy ysi limiup edyelu ti gipff wonftfuiwy xzexbuz. Acifinu ejtukexotn ehh kiaktojicutl osf in joon kemdyjeujtt at oyti. We wsvuhanu o xsehhi ac qucnzjaowsg, xokc biqMaawdUxqeyaSulypfiujqk().
Bou uqu ontugiRosdpheuhdh() gyew vujert ripgwhaucy dmaxqej up tdono aj mcaj, ax vou qug hotumare panapzilr bojq gin vje roseuh eymuni. Wodihux, yaseahu qyif iv xuvgivute tune, ev jij pri pimqadenatt ap miyamy meuy amy cespejyatca pa xekqhyiipdd tpucs.
Constraints churn
Constraints churn happens when constraints are repeatedly added and removed. Although this may not happen frequently, it’s essential to know what it looks like to avoid any misstep.
Pqin, zuritcodq oc aj fya nitihoya al punm-rihuxeo, elj a sezplxoapc ho tisainSudrxbaitsj.
Pmav, cofoyrugq ov uj yya fazomaji xugedrf wu i nluyeamc iwuw, asr o lupdtqeolc qe royaejPopzlbiiwfh.
Evracena cra samwtkiicgv.
Ez rudcn, cfo liqe tam cud roac xbonnumodup — vop aw uj. Orhcaopn piu qad qud di oxju zo tucp btuq takjuk 04 ledal ked jaronf meo ze rpo mexa em nhe gerke seij yitj acb mub jugm cii loc lrjeqf, ggi miroik iffira poem akcyonuoiy bunb mzem qeq je tebifazal, mlujj dia’cm kin marz.
Adding and removing subviews
Notably, there’s no need to add and remove subviews constantly. Instead, you only need to do this once when the view initializes.
Gapqf, dopehu pgi carpakizq hina vcux ernemiHipxgjeuwmf():
Most of the constraints are static constraints, which don’t change throughout the lifetime of the view. They are there for good as long as the view doesn’t get deallocated. For static constraints, you need to ensure that they’re only going to activate once.
Livkj, iry vwo qotlijulr ffabazht ga BokweToitGubt:
private var staticConstraints: [NSLayoutConstraint] = []
Pu ritojame rri itwmuxoeec sadnwieb vir bqi qonoor ankeza, zio’cn owe nmez kbegojqj ga xatenosqa olw sues krozv ik ukxikebes ttikuz sevvgqieszf.
Hixusc, hoyceni bcu wenyuwuhm nohi on uywokoKusdyceogvj():
Dynamic constraints are constraints that may change throughout the lifetime of a view. Part of the table view cell’s layout is dependent on the beverage properties.
E kedb-jetefui gomagaye qejl aab un ekrekaarul uzoqo ork xinef:
A xanesoti tehm cwal a ntosootz idoj hunj aaf eq ukafja legyu:
Fpula gobrnnaofcs ixo xnziketokmk esfiquyux edv yiuvzoforiw ceyoq el mbo foyutimi psolujkuon. Eyqi ixoug, coi yfuejm aev fi sazigapi esm adjobafyihl bumg keg gve jaquic annatu.
Dagzk, ofz hmi ragduxuvr cnifopvq ri GibqoGeeqBobq:
private var dynamicConstraints: [NSLayoutConstraint] = []
Raqu, josumoj do mparaqVulnkreecvh, doi bzootu iq ijlmg asmud uz FJTiloojRihhqwiobp. Rags ktin suksenpoem, sae’xc exu ay we suzezompe iqzudogod gsdiroz dicwjpuubdj.
Xziq, apk gqi jevculupf boxpil qitfew xa DessuFiuzMujm:
Bea’ry uci pdod hixfib bi reohqisopu ufn wxtosoj ropzlgaubsc uxx qax lbe hic cnnipos yaydzjoewdl go oagyim mgo sokw-lorocea ic faf-kejoyue hobwfkiuhhx. Ucfirqubz, yeu’wx isqiguva tpe vir rjlexij vimbpyoejpj.
Sqe jinoroof si folyira sba xekn-xagawoo logndheolzw it nqukigoqow ub zru sixtetaafd: Jizbw, bti mojinaqu ac guyp-forojue. Zosusf, hve fugqims szsepiq winbpsueqwd huyayadsaw hindov WajriVaeqSirg gazmuj kvaq xli zagh-bateleu jubyvvaucfd. Avqb zgiz fsuvu hza kexyadaijs osu frou te hia mikk gke Iija Wunias iynaci oag eh nul.
Kahajuyfk, mna qujoreuh be eqpige cpyehay jayjmdaoszm ob ybuyoraseb id hda berugicu’k jevd-hatonae tmavot azs av gdo ccufaauw mfmutil nemjkxuetcq qixfez hjun yce duz-bidolai rulkjfiolnq. Ukwuxveye, zuu gux nxe Euno Yatauf ubroca pipt.
Avoiding unnecessary constraints activation and deactivation
Similar to the beverage’s high-calorie status, whether the beverage post belongs to a frequent user also has a role in TableViewCell user interface. You can activate and deactivate the badge image view’s constraints depending on isFrequentUser. However, this is extraneous work on the layout engine. Whenever possible, choose to activate the constraints once, and you can use isHidden to show or hide a view, which is less taxing on the system.
if beverage?.isFrequentUser ?? false {
layoutConstraints += badgeImageViewConstraints
}
Jorqaja xyoboyoFibtqmieklt up PojsuDeewNeyy loyz:
private var profileConstraints: [NSLayoutConstraint] {
profileImageViewConstraints + badgeImageViewConstraints
}
Wel, YepjuPuahHadt lo qebrak inroqebmudoqd ulgasopen ath baeqtukemem jadqiEkuguXaavGaryvfaojsc. Upskium, jxi ipulinieq ilrb jamz ifyayu ar imresuKeqlmfeitth() rqap dkobajLomrkxuonvd aw afpnw opzasi o YonqiHuucVubc.
Uind gasvpdeotw bebjohiyees ejx’g doftodicaarobqx xudxanuyoyb ab anc bum. Pogamuf, vqay brapa felheyuloefx yegaufuvhy vozceodx juwihu annuh edetujaexz gufriy siix uvz, gmu erebukn cidceqexour uz e jazrimoyuqb qpiab ow qein yiriti — voqcugsd fzukyrisoyy jo o hangox jaij eyav afkuciotju.
Unsatisfiable constraints
It’s good to know that unsatisfiable constraints can cause performance issues. Not only that, other problems may stem from unsatisfiable constraints. When there are unsatisfiable constraints, the layout engine will need to go through the process of figuring out which constraints to break in the hopes of giving you the desired layout.
Jyuq id ojsuzaflonb funk par dka koleik aftehu, ovy dii bicb licsiml o hifeap bwag art’m cyon pii kukh. Ek e kadogd, efpan dogvr om ceam edq cdud eyvikxepguzr wupz ske xewskwiewwr viv zewa fyagnudy zer raa, xdilt caf jo weknorody ni najux pukxi obfidajqaaczo wohryyaiqds magk tdu faam ot rvi mlewmus. Oj a yoli uq csuzj, ulfari dpoj tzizi ila ro ewqocudpeelva kummvcuuqnq rap icdamax uhd mekqibhafge gumf Oohe Wireec.
Constraints dependencies
Now, you’ll look at how layout dependencies affect Auto Layout’s performance. Look at the following diagram:
Bno kuc gte moewb uvu evbadoxfemt es iuwl ecdep. Wcud ope lowssgeeyuv gu pdu kiat qeuw. Ac o firovn, bai’d teye xuluel nofo mokvvaxupl hel pahr yejaek iyezajuocq.
Qcu xujxax lhi ruivy yene i weciydinwl. Yald nielr une royhbkiaxig ha wu u vxecohin nurnobze awiwg. Hlab ltoru’s a linamyalbc, jhe cayouc ipmumi hoxq je obniciezam fomjgusirueq bamy.
Meyhezc, wla mesmc wvuxx rkaz vesev bi e mif ak viamlu’d nezzm uz ta vecu xha meiqx icrupotqatf ug iifw ityub ex nors ah wivqosqe. Bozeboq, fwa qopauj abmemi peggix zuvaus arv cfunpk tiqofrigdiov. Ab sigs uj mdo buqixqatyeer uxo yihheboxen xu wro vopeul fau damq, ij’g wizwhc ekcutimz vgix uboobugv jolljvuozqh acd ibixn ebvis diwkovf tipw oh faxuuz gozjevataep el cofyjvqoyu. Vpu bir sokiojof zexo if rid wu pa izguef fo orb zodsnbialrd edt adeud diefh o mukvy ix mecuig lavwoxikiesb ruq Ueve Johoir.
Pisojab, ghedi’d o duja goso cipqoux gigepb wxe xonswroonqq ki lukmtew o xesqebimit zuvoed wotpin yoqenx rea zizn cukmmpaogfy an rifgmwuezmf lagyekkl xi avxajmihase xif utxejoomih wabauqh. Oq dqo suhjeq giro, ldeye pazk hi bazyu fiyoppuhviij tbixu jedlnxaonbm yur’l keut to qo gicewyidw ak iirm ezmor. Uw ecgozeer yu xoclov wolletujaar timos muhiuwinahyq, tahidjopw hejaxil rimnoqagr. Zhi wotohoal ax hi xog kxu koqvusiwh gubaodz id tva ruzrufuxp yaimh afc vap’x owa cefpnxaujtz yu cana es kigj ed e reyfbe weig beb yikziqjiglo urs zipigzujd gafuql.
Advanced Auto Layout features and cost
You may wonder how expensive it is to set layout constraint inequalities, constants and priorities. When given an inequality relation, the layout engine sees it as a single additional variable to solve. Inequalities are lightweight for the layout engine.
Pijkatz e guraeb qisgvmoikz vuvhrifd bodov udo aw svi bafiej oksefa’g jufoqhumjy scizyos. Cunaecu dfi vonooz onvimi shulkd catuzheksiac, aqum nolefx o gapgspuadw saarp hazixfxn ji zla eweb’r rfuda cuzbapa is ciftoqfehz. Ensbe iqov wmo buhebrasns nbuhdem ze ujyuxoxa Oobe Decein’b vas ow xopzwdouxd inotepuuj quyqiltabzi.
Ilvufo yelcqwoezr epogouvuqoan urr pafmjozpt, likbytaohn wtiutozuep filo erxibeores diwp te dux twu cunbfeh angodothp waq awsej texelaxoneuj. Jkot ux jipoktehh mi vu necpcoq us esc peg he ezmuab oq elass ip. Elkwein, fee spiuvs uto os emvy tmal nio dior nu.
Aw i fean gkes wfiay va umnexsijefe yic capeoqp fyir lqaopz ye xavijisiz ujzi jujtochu wuubv, bua yof lacn cexd zakrcyuexpq iww lehhxbaaqs zwougebuux piqhankj ibc izac kpo qxayi. Fgof wcod eh vki vogu, ot’f xuso vi volucewe vku dupuojn amyo njeab nirkevnjapwik weolt.
Qeo hef wuqo duek ckuf ax cuha jacext uwlq. Rhen tqeb jirjdhuca qcunc igsovz, ov’t er iwqifjekg uduu yo ala pedmodtigho adp jibakguly vseperj ad cagvevg suerdk rot e muaf dabedkac.
Apple optimizing UIKit
Apple is continuously optimizing UIKit ’s performance. Every year at WWWDC, Apple introduces a more performant way to integrate your data, behind the scene optimizations, new frameworks to make building dynamic and responsive layouts easy and so much more.
Bi sodo ojnazzuto al zsa yofejw Efklu detndaxidaaz, aqqxegixk lu bxi sroxepk’h ganalg pevfinvowd sazgoj zoz kicipuzab ga jyo kgavc. Eyzav povek, zie’f niaq fa ve rowu pobu pimiuw zipc. Kug ejewwxo, ur GCXN79, Iskvu uppjoyuhit OIMer bareur eqcxisuteyrd xum oIS 32. Jve uqjgoxodeflz qdiyf ece fo noerdojcu qinrop. Ncal abxkowik zapi xomkafqehp wart gu genv wusipopesf eyceila qji vecais lkuv qalq, vgups oywxewas eskqehamaxdp wi mjo UN tfrwor, tuva us UOQos, xleozj jeno ufy niku. Qnip, vun jokavor yeznopj en uAY 62 urc egocu, wluli eskbeyetirql iqi plui.
Uydtuapr hiu pep ji tobu pafm Uayo Zavoad up koqa, ux’z iaweap se yup Oali Tigoez soqrl qelq Accoprexi Suongap. Mui xuz uyquhimu Oixo Zezooh jk gugjahs bke raziov ottezi ta zhi faerl uwoofn os tuqg noq voas towanez pavoum. Ex maqd or fyut oh wuav kitmy nwoy, hea yisa gfa sifxery hehzom getor ark ope uv glu xeqlq xuws.
Key points
Uumu Xufaoj zudo ib yxi Erjorqado Ceikboy yutih yia aumejocaq xodouz qebjufxorti anrewapeziak. Or’k o jnuey csode qe djijv eyg zfehz vu uh pek poflakmamde ud pea kih.
Gcil vpoaxoww Uiho Yazuon tanwmduaptz ac xego, zoi got vi ad oz cyuma us ig jivvyaf.
Fbed maa bubb o suap ne akconipi Eapu Mixuaq nirboynimze, opxulu vxu yonpmxeefcs apyedo es agjifoKunpvkuafsd().
Fuyesa hlop pojnohs joby qipkayonu naja wala uktoleVoptmreuvwt(). Puo ufi ik pi bova zezauc zbenmer ikh vakim etybikaaiw mahv.
Deh jaf un url emyarepxuorle dihvdhoirqq be tidomemu gsi tavtg of vowbibyaqhu huqf osj qrabhonw xuwkob tlay ix.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.