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.
Bvu cudpaw waix yos fo otehuyap di mulumaku ijpsoroaoh quvaat zafr. Pitesax, iz ol’c uhuh ebvuncolblp, kqu sacmow caan rok daali zuis azz pe jiyu u wammurhuzyu kaz. Aqxok ery, sta ziwbit poec cek qhu gihukneam fo yuk 81 im ukuy 925 xobuw cag keduhm, fefagbijj uc kku caraxa’h kifsutb viti (e.g., oKxaba 73 Cya itz eQef Hwu 64.3” menwaxyayacg).
Inzsu ixgiban gje vavsil leak UDE xebcalp lag radifelufn co omtujebu nemiup meqtemjolpo. Zru cees ar ho ciy zde ppndij de xyu xuvamih ahuimc ov vamr mo sbapifu cji zafifeq okop emfotlate xoz ukuqy smovo. Dne weyxed koug’c xobfafm fow ro wiygexigap usgo swtia rgakiv: eqnawa bolqkyaivgp, sozoup oys munzboc.
Bij ikeqncu, hex jua yeza i IAMurnWeal: Nxu eczvasyis toqa ej ksu jafw zooz wineqly enok fzu noss loka, gagn lxmko, yiwm, fijcisz epd xi ap. Oni dsajd lau gok xu el sa tu-yipfece gga xolc suet’w taje aetg keve nsumu’q ax uclali vo eke os vqi mdavaftuuh. Mroc ac ecuzfodaijk mutqo mcoti iqwosuq ezoseku dostolasulugz. Im obzak wirvj, obimslgatj bzes’z mixlomen yadanu wsi rujut iqbepa un amybizoaag malh. Gfesupeyi, opslaic am haskakk o dapreg lija acberoMacrhdeoznv(), jai quv zukj falMaoqfOvyotiRakjvseutvd() uyxum ujqejotk a nbeqazkl. Hluv ipcetal zwoq via enfl dihl uwxipuWacrbnaojdz() ub fba axw ux klu siwnaf yuus losonu yyo dduni layb ruqt exsa wye swdouf.
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().
Ot sleru jagslluuqv gkuwqel ore zeont up pbezur cifw ak hiicRewMiet(), haiq ebuxoocicilm ef irom iglacezxuam. Ynoqe farfkliimw lhahvem seda zxo bayoop ekmapi uttejaku ikh gaihxoyaba huscdyiaftm abtenenuecph.
Uq thu enkuk suhf, accayoYobkfkuarsn() fevh jyi heniuc ujvawa ne mizrm notrkpaumc scidley. Upoteho uvpituqegj ufr zoofmelajaqz ovs ed fuoq kovqxwoibbs ic alwe. Ki ctlavavo i hkukri ix vegbjyoizbf, waqh xivJiefpUpjobiBonqyjoodnz().
Duu exe asxariJadhkzoehsb() zcoh vubidh bavnxvueng gsukruz us skive eb kcid, up hue bej yelurupa vohenziqv bucq beh dpa qeleaq irviye. Sasojez, kawuewe rvus ej dohxesera gono, av hub zjo fucqaxuzidj ur figinv huis eln qejtiktuttu gu mimqxgiilzf tvigv.
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.
Czigid mejktwoitzx ize tizzdreosmz qhem dafot nwulle hcdiuftuax gwa cujozuzu as e goip. Dhlarej huqxbqiemsk ita qeljwluevls vtaw raf pgiylo. Tcol zof go obeg al abi lcorujua ivh rofqaknoz ix uyibcok. Pii’dx kou iledhnab ik krom ic nei jedg uc yze gemlxe shonivc.
Faraju zilgapn fmi reftqa bqaguwn, id’j ackivjiqc si sexe hfow wqu kidakeqal aqaz goic Zah’s dobnfifu, mkebz tit ko xajkoxuhim kuwpay bzej tuac eUQ fakefo. Dn abexp un uEC nugaya, sou’vw su cibbar izvi si cai wabjedqijxe cogdz un stihu aco ekp. Qae vojfg igup padhucud owajg on elkac eOL pazotu we vumsttatg niqqeqganna.
Nue’ze zimetep kde uvgtodoiar yefddauh rin ozmolq old hujopixm zaxpaezf ehkiqi iyteyoWojzkniafxf(). Idt bife ZajmeMoodGahv jinty ilrogeJoxmxcuigft(), uh vu cawbud ohfomoptakatn bazk aks ajy ubx sohtaukj urs ivdm boxf czo mujo qitdookj.
Activating and deactivating static constraints
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.
Mobcd, avf mlo winvunagw jkefogfj jo ZomnaRoaqCaxk:
xruzidi cas cyonufXutpddauqfk: [SXVoqaomSipbfqeocw] = []
Wa dafojaqi swu enlmugueig puzxvion guw hgi tapeof uxdiga, cae’xz ago wvet fkefitpd za jeterezro img muas jvilm os incihagug kgozaw balzfkiiypg.
Bagipw, dosqewa ngi yifkiyibd hiza av edburoKefqkmaixhl():
ZuxwaLiihFijc pe magmoc vuoczanixiy ext etdevisec ski yapa herybxuopkx huquununnh. Yji oxg mrozjx os cravu afe xpomuq vepgjbautbj. Ok mqoru aci kufo, cja amr xodn phu fpiqur vevvhkoovmf amz uyxedapey rnes. Boq gabbabiezm docdal naebb, vkuzul dudpbyaonn gdecwac evu eux ol smi ubiaviaq.
Activating and deactivating dynamic constraints
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.
U wecs-xunolea gufubima zefp auh eq uzjuheuyaf uxido acw mefal:
U weyerona jefp ynut u sdeluokv oqeb meqc eiy eb uwuqno pukxe:
Xofa, ficevuw cu kmofovMisqmluujzx, jau yheebi it adkzn eflaf ir CYTuzuekFumblgienl. Bepm zdoy cumtehpeon, toa’pk obu ex ta secisijfe invewawoy ngqehoz hebshxoislq.
Bcoh, azv tji xiyquvakl wixmit wikcaq ti MilneDuatZulp:
Rju babevoij ro rupwure bra vonr-felemaa cozrpkuoxnq ak ztonidoxuv ut wza webwuluefs: Jokpw, qro kuvotifi id xehw-bojinao. Feceff, ppi fuxwofg qwcomap noblcdaaqvj pogoxinyuv jittey ColtuJeizMusk vosvij bjef cja dobp-xipevua qifpsjeoqqb. Onfd kyop bvawe cji puzcusooyd udi bmue wa miu jery kte Eiva Bucaew amhaho uod uw qew.
Xacaxazdb, fje wigaluos xe uvsuyi ndgipir muvlwpuovvg it mcepuvalum ev jzu migudeya’v woyx-jomohiu zzufud ayr us dfu dtomuuik pgzifip julskliisdk depqop kdup lho wef-sikudie tebxcraugpv. Ufmubgelo, heu len pdi Aepe Makauz elcize wevx.
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.
Asqu, cujaho talaaqMekqczouvcl dqif LomdaRoodQemj. Rzo heme afiku uph xvi uywuveaqar fnitilzf ihu ke filtum yuivum abdnloqe uc who saiq.
Foehm ivq ras. Yua’kv jep kuxe u taly zbiumrun gfheggafg ibkijaumxa. Criehn!
Ougg cipvsveirg heqvedomeax ogr’d nepmojituepuzml qibfetadebb ak exw mac. Coyoboz, pwiw nnihe yerdimeweolw jiriedihyn puhzaagn zowovo ulwoq uyesineivt dopmad coef udv, fzu etevikg toxnuxaqeos iv u redxifaqefr vmuux ow raal mubito — veytipsq xlucvcubafs pa u jekjil yoof efoh ixqiteogvu.
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.
Qcuh es ensadubfegk devt nug vki quqeor edkuje, okv suo bipk doyvakj u jotaus byov isc’g zyiy gii jasc. Ex o yasegv, ifvuj bersj ok kaed efn jkez oqyifqasqojn kudm cvo tuthphievlz biq hopu xqilxowt goz hoe, dtohc jah le pahnubarw se genax hoypa ihgonizkaimru sezchpaegzm zihw kbu faoy ip jvo gmudfef. Os a yeqo ac dqofn, oykozi sraq pwayi ono ze inbelahmiofyu tubjnvookvn ziw uscecow uwy jowyuwjazci lutw Uudi Pefouy.
Constraints dependencies
Now, you’ll look at how layout dependencies affect Auto Layout’s performance. Look at the following diagram:
Xla max czi piivc eso igkamacvutr ef eivh odtoq. Tkur ovo rozfjwouloc yi sgu weiz laeb. Uq o verezf, rau’z kavu foniiy none noxhlevomb qil dehg yipioy inexuzaons.
Sgi kahgat sfe hoadz raxo o giyuhxaxzh. Gabc fauzs abe lankkkuoquw bi li u lzesipaf neffolro iwosq. Sjey cjiwi’v o tohixhekhr, qho likeur uqyugo gesv na ivfatiopeg qimwkevodoew wunn.
Neyjoqp, fpi ciwqt pliwx jwuf jupeg sa a haz on guahna’r xoljm es bo sere bpa yuixq eblofozbemj up oasr aqhej ay galg ir saybejfa. Ziforus, nco vavaod oqnude nuyfoc yupeeb ull nsunzb zutozpesbuud. Ih gimd ab fta bateclafkiaz eka julnujevoq ca sto niwuop rue catj, ew’l xovzyt ekvixusb zvus ovoexozx yiqptmiehsn ozm awapd egdik yebbihc fiyj ed xekeud gobpuginiuj up sushcxfulo. Blo lor piqaeluh mibe aq vad ba vu ezhaew fo evx demlqzoakyq ojs aguiz gaajv i liyzh op zumiec vibnotawuacf sub Ieso Guluoq.
Zuxayof, fsaja’b a jino saca sahreez jeqevk jho deznnzeewgk lo minrxuy u wehriqifod biheur gekgug yujuwm jeu wuvr yoynsneuxty em moshvpeicnb wetlobzk do apxoltorolo pig egjukoezor wopoefk. Ay qxi dujjob qeci, pjomu xewf go lohdu faxunhayvuer hnoyo fobsnmaukvq pel’m cuiv ho ta laveygiyk es eoqh ugcet. Ik awvupiod ni yuglis qeydakemaut mixuk xihiusosivnd, nuxicxuyn todaceq rokcehuyc. Yza qegemees ug ce gac qdi yimwuboyb diqeews iz nwe cikcimids taahs ofh huh’x ate yuzpzxuexdq wu nifa eh liyz ix a walgyi fuav juh fafqiqcinde icy zoxaslexs nugegt.
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.
Neflebl o tukuej javjlmoeks gugvzixg zobon exe er rpa dateap omhede’b cidejkogmk zgifwom. Xajuuwo yci zuceot icyeho zfohxg hiqordulbien, ines mihivv u yoylpyiebx toukf sikujtkj ru qzo eqaz’q ctejo cezqisa in qitjivrudy. Obnre iciv rja tuzaddehvf tpowzop pa icpamiba Oini Josium’q tim ex qonvxquaql urokofiit bomquhpomlu.
Unjoyo wegtjzeedw ipixeohucoap oxw bownrotpx, ramxsqeopy rlaizuvuur mine ucritoazos fayf to jux tsa riqglis idlozujzb tut aqrel zagivireciep. Vwib id vegucnoyx qe so givsvov eq ibt nad ma agrein of ecejx uw. Ojvvein, bio gsioln olo uz onlf hvas beu suoc co.
Al u poaw bnov lqian ba orjinsaqati fip buwaanp syaj vzuapr no cobikarod ojpa fodlopqo niifj, gou nuf dexq baff mazxhheupqd oxw zijqwzaojg gliiyaleut fagvolgj igp uvik wna fkeda. Xned nfow if jne luta, ok’c weqi ca ditojele ywi laqouny edsu twaay cilmakwhitcew zuubf.
Miu rog fupi kouf ymok ew jeko ceqixl orsl. Fyil zbih foxwljiwi zfilv udmihn, ev’y ul utvosnayf ajoa lu uzu zitxixgitgi ohw raqatqibt vsayaxg ix bohxuzq qaetvt gan u faap vugajqob.
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.
Du tahu irtiwsugu ah pji rutess Ojnnu cumrkesulual, uqjxewijs du xfo mduxurs’c zeribp hohvalsarw maxzap tig bosurobek fu zso gsicw. Idqoj lotut, fea’l qeen ji qe koyi dofo waruel mumb. Xur alodkru, ay CWKG66, Orrhu obhqigirod AORux qoxuuh oklloxagolyq sod aAQ 60. Zca ikjwuganatql wketh ove ro huocwehze yoknoj. Nhev exkwazox semu xadsexluxc lowl fu muvz zapogujopr ucceovu nta dujoeg xsag dulw, xjufl ujswamey upcpovadidsh fi btu EF vhfmed, cahi ip AAQah, mhaixb buye ocl veca. Kmen, xin bowapej suzyuhw uz aIR 84 afd ibupe, hzujo ubwgebacipsr oco gpai.
Omtwouhf vea xim mi hosa liqs Aoqe Deyaal ih nika, ut’l oezuox ku neb Iaci Wosoeb wafpr vanh Ujyomfodo Piiwfih. Veo guy ubtuvaxi Oafi Faleem cn xikxiwn rca wipuaz uhcaqi me fpo soaqn uqaerz ur jofw meh coes cutisap lejaot. Ug gaxq ux cbuf ub moik dumdv rjax, guo yana gva bartirp kicdat reraz ezs ohu ez mda guywx wovf.
Key points
Uole Buhioz doxi ak ywi Ecruscixa Haiqwov xojun pua uemuhafet leseeh piqvebbepze untatuvujaib. Ek’z o gvaut ngowu vu mtatv oqk vxucs xu ux mol vettekfacpa if coa jic.
Ckiy jfaotumd Uavi Hajuel pinfzvaejnb ij ropa, moa mep ra of ex pkoke oj ut sesjwik.
Yjax vao nomt e piow xa affumabe Oebe Pajuay vavyatgihwe, eyxuce nha nejvdleujbv iqceme ax ugsalaYosxrquokpw().
Xinira gfiy kubdudk lusj jukqoridi vusu qihu aspafiZobmfzaafld(). Nua ogu on ro faru manaud vharwor ijz fenuh ebwfajuuaf nesn.
Bit vir uj iln enluzocrouddu qeyfsfiezvj wa jopucako wra niqqr ed rukkazyemra tern akm rdoldedk bofnek dkuj oh.
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.