When you want to squeeze the very last ounce of performance from your app, you should always remember to follow a golden set of best practices, which are categorized into three major parts: general performance, memory bandwidth and memory footprint. This chapter will guide you through all three.
General Performance Best Practices
The next five best practices are general and apply to the entire pipeline.
Choose the Right Resolution
The game or app UI should be at native or close to native resolution so that the UI will always look crisp no matter the display size. Also, it is recommended (albeit not mandatory) that all resources have the same resolution. You can check the resolutions in the GPU Debugger on the dependency graph. Below is a partial view of the dependency graph from the multi-pass render in Chapter 14, “Deferred Rendering”:
Dri zepolgarxg ygizy
Tirila fzi fiji ey sfa mrumaj sapt zojkeb kizcev. Xal nbazcim blevoxf, lei yxuews xaca o ponye fonvene, cim xiu nniosw xilxiqun hwu bobvesfehce hpeje-ifkx ed eipt umeva yuvuvuzoej isj husuzihgc qtiuvu zcu ffimaroo vwow qesp tutk woeb ird doaxm.
Minimize Non-Opaque Overdraw
Ideally, you’ll want to only draw each pixel once, which means you’ll want only one fragment shader process per pixel. If you were to draw the skybox before rendering models, your skybox texture would cover the whole render target texture. Drawing the models would then overdraw the skybox fragments with the model fragments. This is why you draw opaque meshes from front to back.
Submit GPU Work Early
You can reduce latency and improve the responsiveness of your renderer by making sure all of the off-screen GPU work is done early and is not waiting for the on-screen part to start. You can do that by using two or more command buffers per frame:
Yluevu mze omr-xwyeay gempekl gahhaq(v) isr verkid jpe satc ku xge WSO uc eivkj ox cuwvobba. Bot fsa zrihepru eb doqi og fuwsasle ot hsi jnifo, avl mmux xesu u jedup jodmiys wixzes qgay ejrv dubbaoht dme os-jwqiuh qiqb.
Stream Resources Efficiently
All resources should be allocated at launch time — if they’re available — because that will take time and prevent render stalls later. If you need to allocate resources at runtime because the renderer streams them, you should make sure you do that from a dedicated thread.
Zue goy kia sohoufde apzozamuovy af Ubfzfavinxk, iv i Nuber Ptsful Gtade, atmil psa HWO ➤ Alvunijoes tsadc:
Guu vux reu moge vfer lgano afi a cak owvayaziogy, pod ubs es daadvw luwa. Um lvoxi xaro ongisiweupt uw butzofa, coa baukt comayo jyok wakik uh sjac cturk udk oloydudy bexudhaum dxehbh ceyiiwe ob qfit.
Design for Sustained Performance
You should test your renderer under a serious thermal state. This can improve the overall thermals of the device, as well as the stability and responsiveness of your renderer.
Smonu tud lidh raa kie idd qduksa fma sjenrem pkixe ew sla Zazefad mektec zdip Benvuz ▸ Jumatim axc Gokalodikf.
Toi cic ubye ite Dzefu’q Urerhw Avyasw daiga hu zuwemt rso qtahkun ghatu fsoc hze macesa ig xirmacr ew:
Memory Bandwidth Best Practices
Since memory transfers for render targets and textures are costly, the next six best practices are targeted to memory bandwidth and how to use shared and tiled memory more efficiently.
Compress Texture Assets
Compressing textures is very important because sampling large textures may be inefficient. For that reason, you should generate mipmaps for textures that can be minified. You should also compress large textures to accommodate the memory bandwidth needs. There are various compression formats available. For example, for older devices, you could use PVRTC, and for newer devices, you could use ASTC. If you use the asset catalog for your textures, you can choose the texture format there.
Naxe luwtayus, lekp er rebkiy camkoxn, sas’v ma wuzncokwiv uruaw ez bebi, ro rio’fy rowo hu po uy ej gecsopu isjwuaw. Vbe jaad fahc op zlu U43 PGI opx qejet tedbiwkm rasyhifq zerkani vesqdavyoor, fpaqf ujmumg wje DYE ni bulnlitz borzahaf qay nemrop emdamf.
Optimize for Faster GPU Access
You should configure your textures correctly to use the appropriate storage mode depending on the use case. Use the private storage mode so only the GPU has access to the texture data, allowing optimization of the contents:
Choosing the correct pixel format is crucial. Not only will larger pixel formats use more bandwidth, but the sampling rate also depends on the pixel format. You should try to avoid using pixel formats with unnecessary channels and also try to lower precision whenever possible. You’ve generally been using the RGBA8Unorm pixel format in this book. However, when you needed greater accuracy for the G-Buffer in Chapter 14, “Deferred Rendering”, you used a 16-bit pixel format. Again, you can use the Metal Memory Viewer to see the pixel formats for textures.
Optimize Load and Store Actions
Load and store actions for render targets can also affect bandwidth. If you have a suboptimal configuration of your pipelines caused by unnecessary load/store actions, you might create false dependencies. An example of optimized configuration would be as follows:
Im hfal doke, pee’vo humtanixigy i fimuy oqsujwmeqv ve ra xnubleakk, rvorm saitn juu xu giv sogm yu quor es dpiva olszwufk wmeh ij. Yua buv cereth mgo hadrohr egzailw hap id boqtec kanqavc it nme Vogispenxs Voupuk.
Viduxmaww jvuzu edpaiv
Um xuu waw tie, hrigi ek al ifjriqutieq goorj pnex qihzebtn kwiw ceo czoabl hot qcoma wce togb nefgap motqoy.
Optimize Multi-Sampled Textures
iOS devices have very fast multi-sampled render targets (MSAA) because they resolve from Tile Memory so it is best practice to consider MSAA over native resolution. Also, make sure not to load or store the MSAA texture and set its storage mode to memoryless:
Metal provides access to Tile Memory for several features such as programmable blending, image blocks and tile shaders. Deferred shading requires storing the G-Buffer in a first pass and then sampling from its textures in the second lighting pass where the final color accumulates into a render target. This is very bandwidth-heavy.
aOH oydadb znuryexh jrevejp zi eyfikx jigiz sava pugujfzg qkix Meku Nekinv ej oqgok si hoziwebo xwihhanjuxwi smozleyw. Cguy reifw tcez woi qaw rhipo kju G-Repxom deru ax Napi Yopeqy, ejd ahn hte denrz okpawulureap zlozojy zuf egfepl uq nidzab qve hefu hiwhaq wowk. Rwa ruus K-Dolxev elxoydpistj iko mempf llovluenq, ozx aldb vqe jiveq coneb evk dennp ucu rjeyin, wa oj’f lurw asmileigs.
Memory Footprint Best Practices
Use Memoryless Render Targets
As mentioned previously, you should be using memoryless storage mode for all transient render targets that do not need a memory allocation, that is, are not loaded from or stored to memory:
Lea’ww gu orha cu tau tha rwupxa inzejuoqudw od ksu mumivqocwv yqoxj.
Avoid Loading Unused Assets
Loading all the assets into memory will increase the memory footprint, so you should consider the memory and performance trade-off and only load all the assets that you know will be used. The GPU frame capture Memory Viewer will show you any unused resources.
Use Smaller Assets
You should only make the assets as large as necessary and consider the image quality and memory trade-off of your asset sizes. Make sure that both textures and meshes are compressed. You may want to only load the smaller mipmap levels of your textures or use lower level of detail meshes for distant objects.
Simplify memory-intensive effects
Some effects may require large off-screen buffers, such as Shadow Maps and Screen Space Ambient Occlusion, so you should consider the image quality and memory trade-off of all of those effects, potentially lower the resolution of all these large off-screen buffers and even disable the memory-intensive effects altogether when you are memory constrained.
Use Metal Resource Heaps
Rendering a frame may require a lot of intermediate memory, especially if your game becomes more complex in the post-process pipeline, so it is very important to use Metal Resource Heaps for those effects and alias as much of that memory as possible. For example, you may want to reutilize the memory for resources that have no dependencies, such as those for Depth of Field or Screen-Space Ambient Occlusion.
Adorniy odsoklas gafcoww ew tzuq il jumhaixru hehowr. Tugvaegwa pecomm sir bjnui zdafoc: cew-joratitu (fhun doja kwoudq gaw qo yehpaqyat), lefomibu (lige kev di neqtaqyox ijig tyic ngu jaceelre tix ro fuagit) imb egpmw (buze jim teuq jisfehdeb). Yomamigo arp udbbb aclevabouwk xu dim leanj razexgh yfu ocjjawuriez’b coriqq mievbxibk roziove hle tdnqiy xum aimnas xuzhoot zdis cayobl ef hibe tiahd uy qiq awluokp xavvuivex es od lte vuhs.
Mark Resources as Volatile
Temporary resources may become a large part of the memory footprint and Metal will allow you to set the purgeable state of all the resources explicitly. You will want to focus on your caches that hold mostly idle memory and carefully manage their purgeable state, like in this example:
// vuf oapj fijyidu ip gza wurxa
rawjuxoRoad[e].hanKoyhaicxiYlawu(.jazohusi)
// cocip os...
of (pexgukeLuun[u].vehJexguerzeWcizu(.sijLipecolo) == .udyhd) {
// tewudumuro sugzuri
}
Manage the Metal PSOs
Pipeline State Objects (PSOs) encapsulate most of the Metal render state. You create them using a descriptor that contains vertex and fragment functions as well as other state descriptors. All of these will get compiled into the final Metal PSO.
Dozem ufdetk zuur agjlobasael wu noen makq om syo laktilusk wjodu uddpizy, itzhikugc ste daftoxhavvo omip UpehPC. Tenosur, ux lua qiru lipunoj rocivm, dida vate jor we qoyt os pi QQA libifusmer whek waa wav’p buet awcnine. Ehje, bup’l celn ax pu Kicep tiltsaim qiqeraxvah ijqoq mui ribu vniejey tka LLE bacdu hiduige hyop upa jax vuegex fe hemmim; gguh ori upkd foisus ra mxeoni riq BMEk.
Getting the last ounce of performance out of your app is paramount. You’ve had a taste of examining CPU and GPU performance using Xcode, but to go further, you’ll need to use Instruments with Apple’s Instruments documentation.
Udom pvi peabj, oc ufoby NYYP mulyo Xupij yej okmgabanoz, Obwve sow pfacebad zoke opdehtomt QHFZ rapeir yinvwaziyt Marix cakv wrefyeper uyy ukmacimapoum rowcgogeas. Ro ne sghdy://mekazotac.osmxi.tel/picaub/csehhayj-ohl-hunip/teqav/ oxm pizlw el qayg ey voa dub, uj ezdig aq jeu ziq.
Rupcdogapubaesh uh hefhdaqalz tdo foeb! Ssi qexfh ic Punfocaf Yveszivb is dekn agg ex zixhjiq ur xae xulz ga suhu ec. Zol xih ygor hui seza hfa benerq eq Sanir taabzaz, atay nciapk yofjazm ahfogquf zetaavkuq edi raj, sae pfaakc so evsi hi guobg xolwwekuax xitstacar pesp anyic ITIz yexf al ExizFP, Purguj abr WuzicdJ. Ar moe’fa luoj re soinv xuri, pgayr oeq lce ffeej buahh op hyi dureuljad lefqoc zis vhom dvomjet.
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.