Detect and Avoid Common Performance and Memory Issues in Unity WebGL Builds

Rate this content
Bookmark

This session explores common performance and memory issues that arise in WebGL builds produced using the Unity game engine. Examine how to identify, troubleshoot and avoid pitfalls that may lead to out-of-memory errors. Learn how to reduce game instability and improve game performance in WebGL builds.

10 min
07 Apr, 2022

Video Summary and Transcription

Today's Talk focuses on avoiding performance and memory issues in Unity WebGL builds. The importance of managing memory and keeping the heap size small is highlighted. Techniques such as using asset bundles or an addressable system can help reduce memory usage. The limitations of garbage collection in WebGL builds are discussed, along with tips for optimizing Unity code. Tools like Backtrace can assist in debugging memory and performance issues.

Available in Español

1. Introduction to Unity WebGL Builds

Short description:

Today, we're going to see some of the ways we can avoid common performance and memory issues arising in Unity WebGL builds. Memory is a major constraint when running a WebGL build in a browser. Unity heap is where all runtime objects are stored, and it's important to keep the heap size as small as possible. When building a WebGL application, Unity generates a .data file that contains all the required assets and scenes. To reduce memory use, you can use asset bundles or an addressable system. Garbage collection is also an important consideration in WebGL builds.

♪♪ Hello, everyone. My name is Oz, and I'm a game dev evangelist at Backtrace Source Labs. Today, we're going to see some of the ways we can avoid common performance and memory issues arising in Unity WebGL builds. The first point we'll be taking a look into is managing performance. And a major constraint running a WebGL build in a browser with good performance is memory. So, in terms of memory, what are the problems and what are the considerations that we got to take a look at?

So, as you know, the complexity of the content you can run is constrained by memory. The memory is allocated by the browser, and the amount of memory it has available varies on a number of factors, including the device you use, the operating system you use, which browser you use, and whether it runs on a 32-bit or a 62-bit browser, and a couple of other factors. So, to understand how memory impacts performance, it is very important to first see how memory is allocated in a Unity WebGL build. For this, we need to take a look into Unity heap. So what is Unity heap or a memory heap, as Unity calls it? So, basically this is where all runtime objects are stored, and these could include native objects, assets that are loaded, scenes, shaders, animation files, as well as other managed objects. So it is worth noting that this heap is one contiguous block of allocated memory. Until a few years ago, you had to allocate the max size of the heap in the build settings, but now, Unity supports heap expansion on demand, depending on the needs of the game, and it's expandable to up to two games. However, the same feature can actually often cause your game to crash, especially where the browser fails to allocate one contiguous block of memory, and this is exactly why it's very important to keep the heap size as small as possible.

Now, to understand how we can keep the memory heap size small, we have to first take a look into what Unity does to all of the assets and scene data in a browser, and what happens when you build a WebGL application in Unity. So when you build a WebGL application, what happens is Unity generates a .data file. And this is basically all the assets and scenes in the application that is required at the time of launch, and all of that is packed into a .data file, including Unity's scenes, textures, models, UI's price, audio assets, shaders, and pretty much everything else that you need for the game to run. And basically Unity WebGL does not have access to a real file system, therefore it has to create a virtual memory file system, and the browser then unpacks the .data file into this particular virtual file system. And the browser, while the game is running, keeps the data uncompressed. Now imagine if you have a complex scene with all sorts of assets, right? Including 3D models, shaders, everything. So you can see how possibly it can run into memory issues and slow down the game performance as well. So the question then, that arises is, what can you do to reduce memory? Well, there are a few techniques that you can adopt to reduce memory use. And one way, the most common is to use asset bundle. So you could put all of the most frequently, but bigger assets into an asset bundle and load it, unload it on demand whenever you want. And it's also worth noting that the asset bundles are directly downloaded into Unity's heap and therefore they avoid extra allocation done by a browser. If there are big bundles, one technique is to possibly cache the data and this is basically one additional thing that helps you to avoid redownloading each time you actually play the game. So the third one is something called an addressable system, which is an alternative to asset bundles. And sometimes it's started as a better version of asset bundles. However, it does have some of its own share of problems, including supporting WebGL builds out of the box. But there are some workarounds that exist to make it work. The next important consideration with regards to WebGL builds is the garbage collection or GC in short.

2. Unity WebGL Memory Management and Debugging

Short description:

GC in Unity WebGL runs once after each frame due to limitations in JavaScript. Manipulating strings can cause performance issues and memory problems. Examples include updating a countdown timer text and using enlarged for a loop. To optimize Unity code, use StringBuilder for string manipulation, cache arrays before iterating, and use CompareTag instead of comparing strings. Tools like Backtrace can help debug memory and performance issues. If you have questions about WebGL or Unity, feel free to get in touch.

So typically what GC does is it locates and collects unused memory and then reallocates it into the Unity heap. On other platforms, when you GC runs, all running threads are paused to give time for the GC to check the stack. This is not possible on WebGL due to limitations in JavaScript. So what Unity does here is it simply runs once after each frame because the condition for the GC to run on WebGL is that the stack has to be empty and this happens only after each frame is rendered.

Now we'll look into some of the examples of code that increase GC and reduce performance and how we can actually write a better code. So in the first example that I have here, you can see how manipulating a string is a major cause of performance issue and sometimes can also cause an application to run out of memory. And the primary reason this happens is because any manipulation of string causes Unity to create a new string each time and this can quickly add up. For instance, if the code were to be part of the update loop. This example you can see here is where you have countdown timer showing on a UI and the countdown timer text is being updated continuously in the update loop by appending the countdown prefix with the countdown value. And each time you do that, it's creating a new string which can quickly really add up and it's not good for the memory. On the right, you can see how this code is being rewritten into a better code where we separate the label and the value and therefore avoid the string manipulation altogether. Here's another example of string manipulation. If it's using enlarged for a loop. You know, in a non-WebGL build, this might run as fine as it could be because the garbage collector will be involved but not so much in a WebGL build because in WebGL build it doesn't get a chance to get involved until the end of the frame and therefore this will likely run out of memory and crash. Here I do have some other examples where you can optimize Unity code to reduce memory allocation and reduce the need for frequent garbage collection. So when using strings, for instance, if you need to manipulate and pen string, use StringBuilder instead of Plus. If you're using Unity functions where the function would return an array and you have to do some array manipulations or iterate to an array, so you should cache it before you use it in a for loop. For comparisons like comparing a name or tag, not many of us know that these accessors actually return a new string each time, so it's better to use, for instance, to compare to a tag, use CompareTag function. And last but not the least, in case of coroutines, one common thing we tend to do as programmers is to use a line that returns new WaitForSeconds or WaitUntil or WaitWhile. So instead, cache it and use that, especially if you're using it in a for loop.

While we spoke about the ways memory can be managed in some situations and how we can reduce memory use, there are some unexpected situations that can cause applications to run out of memory or cause applications to even crash, so this is where tools that can help debugging these issues come into play. So one of those tools is Backtrace, which I use in applications and games I make for any platform. And of course, WebGL is no exception. So when I integrate that, I can see errors in real time and dashboard and help me troubleshoot performance and out of memory issues. Things like what we see today, these can be actually used and then that information can be collected to fix further problems before they get out of hand.

That's pretty much the end of the session. If you have any questions about WebGL or Unity, please feel free to get in touch with me. My contact details on this slide. Thanks for tuning in.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Building Fun Experiments with WebXR & Babylon.js
Top Content
During this session, we’ll see a couple of demos of what you can do using WebXR, with Babylon.js. From VR audio experiments, to casual gaming in VR on an arcade machine up to more serious usage to create new ways of collaboration using either AR or VR, you should have a pretty good understanding of what you can do today.
Check the article as well to see the full content including code samples: article. 

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
JSNation 2023JSNation 2023
116 min
Make a Game With PlayCanvas in 2 Hours
Featured WorkshopFree
In this workshop, we’ll build a game using the PlayCanvas WebGL engine from start to finish. From development to publishing, we’ll cover the most crucial features such as scripting, UI creation and much more.
Table of the content:- Introduction- Intro to PlayCanvas- What we will be building- Adding a character model and animation- Making the character move with scripts- 'Fake' running- Adding obstacles- Detecting collisions- Adding a score counter- Game over and restarting- Wrap up!- Questions
Workshop levelFamiliarity with game engines and game development aspects is recommended, but not required.
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
JS GameDev Summit 2022JS GameDev Summit 2022
165 min
How to make amazing generative art with simple JavaScript code
Top Content
WorkshopFree
Instead of manually drawing each image like traditional art, generative artists write programs that are capable of producing a variety of results. In this workshop you will learn how to create incredible generative art using only a web browser and text editor. Starting with basic concepts and building towards advanced theory, we will cover everything you need to know.
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
JS GameDev Summit 2022JS GameDev Summit 2022
121 min
PlayCanvas End-to-End : the quick version
Top Content
WorkshopFree
In this workshop, we’ll build a complete game using the PlayCanvas engine while learning the best practices for project management. From development to publishing, we’ll cover the most crucial features such as asset management, scripting, audio, debugging, and much more.