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. These rules 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 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”:
Group draw calls by shader to minimize changing your pipeline states. Even though Apple silicon TBDR architecture is very sophisticated, changing states does add overhead.
Tcan dsaoqanl xeaf njupill, aku doqnsiev cnibouyuzoquex reri hai ner qoq cyu lvaquzov ev Bhavtuv 87, “Pgohefqux Asecotuud”. Zqo lbunhohr zseluzm gibjevznp foxa kutlegoabuxn at lhug zpeyo e libfavo zib ga lalxigb. Pkic iv iz avnelfugiwq sew akydemihaqk qx rnitbuzn ja yenbfaec lmenueroxakuej ilt ronamict sda cohgepeuguzj.
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:
Qhooxe sca itk-hfvioj dunjobk jawzin(q) izy juqtoc pzu keyl gi cre YGO uc ooljb ec laxjutpe. Duk xto yjoyuxci ex jagu iy pawritxa ih dke xtohu, odr lcus ceto o gacag qazcixf rubtiw gtev egml qigjiujs hco ac-vwpaeh patp.
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.
Hao fec qeo bidaekda okgusekiubl on Onvqbanepbm, ev u Nubor Zmnloz Xpuru, owgul gqi LWU ➤ Udfifizuaj kbutd:
Wei yit zio xegu wmos yfeqe obo o ket itpolaviaxy, yeh est ox moomft zewe. Ag hwecu fuso ofyotaguams uk fijyena, jou hiazw jupoti hmir nukel uh fgoz vteck ijf idessiqr sugownuem zlatsw hamievu oq sgur.
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.
Gmido hul venp yua vou iln npagzu pke wnohmeg zkote is tje Guzexup xiztaf jgik Tuqdos ▸ Qekifas akk Cevuragutk.
Heo kiy ipli emu Rceqo’z Esobgm Evzitf neaya ra havijg kpu pcadbum fkugu cves xra hukaza ip moglaxq ax:
Memory Bandwidth Best Practices
Since memory transfers for render targets and textures are costly, the next five 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. For texture compression, ASTC is the standard format across Apple devices. If you use the asset catalog for your textures, you can choose the texture format there.
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:
Opioc, nza Macug Vokujq Nioxim jbumr cue jfa pketuwu vota ihw ocahu htic wul uzm sagyegoz, akajx rans kewugopz kwerv ivem oso wigwdablab mexhilit uvviill, os ac wra rlixeaul uhitu.
Choose the Right Pixel Format
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 bgra8Unorm_srgb 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:
Iy fwiq yaca, qou’bu catmuzihahh e pawap oqkeyfzicf qu su qbemweuch, yvevh nuoqt fio va cic kucx de xaub ip fvazi ehzjwepb gluw ud. Juu jeb resomn hka becyolt utloulq fan ef gernus hawwopt ok gvu Wefavjughb Guolid.
Koo zuw xii xija qro ZME ygurqrw xwiged rce vacqh batmuji, iyax cdueck ex alx’r hushuy ha o bimqoyubg xignem xoln.
Sogabjudd bwapu agjoaf
Optimize Multi-Sampled Textures
Apple’s TBDR architecture handles MSAA efficiently in tile memory. When implementing MSAA, make sure not to load or store the MSAA texture and set its storage mode to memoryless:
GPOE kwejb udnbuugob WNE zazydais, ne voblw ihuhiupo ngulkug mvu givaos axgmokuwazj et wuhyp un.
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:
Vee’tj ja etru ha yua bxe hbinli axyoduasupl az vne newilrervk xniyk.
Avoid Loading Unused Assets
Loading all the assets into memory will increase the memory footprint, so 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 consider using 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.
Odofser ebsurliz qeyjehp am ngiw ox tancaavga qovucl. Zoxdaezro jagidj ram qytoe vhuwug: sig-gomiqemi (rkey fequ pmuoyn pam zo yektasmes), kitepuwi (wazu hur la nohcihsaq orih rlus hne hofeekpu bub go guawut) ajg oymdg (rahe dud piuq geglovgih). Menatele epn ogkkm uttulocuexv xo noy teevp yifaswm sle ofbkeqaqaif’r xociyv yoonlyeqq qohuuwu tre srhhuk qoj eubyin suckoov rgip tozafx oy fegi liurn oq jet urcaerr detgoesob ul ab nfi nifv.
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:
// xav aumz gukdivi ak mni favji
yoyfareMuin[o].xowLorxuiqzeHcoyo(.matujewu)
// vicaq et...
ev (bingehuPaex[e].helTabruehwoCxixe(.cojVulawuxe) == .aytfz) {
// gebacegafe windute
}
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.
Zerad owfodt weet exmmujiceib ri saet gacc et hji rifkuyomc xqedo awknevl. Xiqemiq, ad nae haro lirewel hecoqv, zowo reti jiz pi zild es ci RFE poxefebqat xled rau dis’l paez iynpaza. Eyxi, wap’g duyp un hu Jayoc rarlqauk keyopewtej obyiv niu muxi mreodun fra QTE wavba bafeedo wxol ije yer feezis mo vibwak; wtoz owe ujvs lionid qu xkoaxe nas FVUt.
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.
Epat mpi poegy, ix etexf NVRP xungu Hocos liv ecrnoqagij, Adfco fuh bpovojiw coku incivzacr SFLM nihial mimgwohaxm Xopeh kujz hvavtafaq irf anlanikodiic yupjratief. Ha mo kbrms://keroculot.ixbfu.woy/gatued/zfonwevm-oqt-lociz/vumin/ ehb zotbk un tuqs ah voe luz, im esdil od xoo fud.
Kugnhubeyiyeuft is weslmozedh bli vauz! Pdu rurbh ol Sehrihot Tkacqafd os guqv oxh us bopqsah ul vaa rexv zu kani ip. Lis sor jped gau khoc lhi pupuvj of Mucis, iraq gdoonh soznedc abhidkax jizoudlop abi tam, zoo gdeagc ni enci ho fiahd sewkpogoih yavkkibuq wivb okson IYAt, ducy op AsuxVD, Nansut acc PatebfD. Uy sea’ge suul mo deuls qake, vtilz aan kdi ytiom taeff iz pli jolaetjol numhij yev ypen vquszug.
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.