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.

This talk has been presented at JS GameDev Summit 2022, check out the latest edition of this JavaScript Conference.

FAQ

In Unity WebGL builds, the Unity heap is a contiguous block of allocated memory where all runtime objects are stored. This includes native objects, assets like scenes and shaders, and other managed objects. Unity now supports heap expansion on demand to accommodate the needs of the game.

Memory allocation is crucial as it determines the complexity of the content that can be run in a WebGL build. The memory, allocated by the browser, varies based on several factors such as device, operating system, and browser type. Effective memory management is essential to ensure optimal performance.

To reduce memory usage in Unity WebGL builds, you can use asset bundles to load and unload large assets on demand, utilize addressable systems for better asset management, and cache frequently used data to avoid re-downloading. These techniques help manage the memory heap size efficiently.

Unity handles garbage collection (GC) in WebGL by running it after each frame is rendered. This is because JavaScript limitations require the stack to be empty for GC to run, which only occurs post frame rendering. This approach helps manage memory but can differ from other platforms where GC pauses all running threads.

String manipulation can lead to significant performance issues in Unity WebGL builds because each manipulation creates a new string. Common scenarios like updating UI text in a loop can exacerbate memory usage, leading to potential crashes. Using StringBuilder or separating label from value can mitigate this issue.

Tools like Backtrace offer real-time error monitoring and dashboards that can help debug performance and memory issues in Unity WebGL applications. These tools provide insights and collect data that can be used to address and prevent problems before they escalate, ensuring smoother gameplay and application performance.

Oz Syed
Oz Syed
10 min
07 Apr, 2022

Comments

Sign in or register to post your comment.

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.

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

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Speeding Up Your React App With Less JavaScript
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Watch video: Speeding Up Your React App With Less JavaScript
Mishko, the creator of Angular and AngularJS, discusses the challenges of website performance and JavaScript hydration. He explains the differences between client-side and server-side rendering and introduces Quik as a solution for efficient component hydration. Mishko demonstrates examples of state management and intercommunication using Quik. He highlights the performance benefits of using Quik with React and emphasizes the importance of reducing JavaScript size for better performance. Finally, he mentions the use of QUIC in both MPA and SPA applications for improved startup performance.
React Concurrency, Explained
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
Watch video: React Concurrency, Explained
React 18's concurrent rendering, specifically the useTransition hook, optimizes app performance by allowing non-urgent updates to be processed without freezing the UI. However, there are drawbacks such as longer processing time for non-urgent updates and increased CPU usage. The useTransition hook works similarly to throttling or bouncing, making it useful for addressing performance issues caused by multiple small components. Libraries like React Query may require the use of alternative APIs to handle urgent and non-urgent updates effectively.
The Future of Performance Tooling
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Today's Talk discusses the future of performance tooling, focusing on user-centric, actionable, and contextual approaches. The introduction highlights Adi Osmani's expertise in performance tools and his passion for DevTools features. The Talk explores the integration of user flows into DevTools and Lighthouse, enabling performance measurement and optimization. It also showcases the import/export feature for user flows and the collaboration potential with Lighthouse. The Talk further delves into the use of flows with other tools like web page test and Cypress, offering cross-browser testing capabilities. The actionable aspect emphasizes the importance of metrics like Interaction to Next Paint and Total Blocking Time, as well as the improvements in Lighthouse and performance debugging tools. Lastly, the Talk emphasizes the iterative nature of performance improvement and the user-centric, actionable, and contextual future of performance tooling.
Optimizing HTML5 Games: 10 Years of Learnings
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Optimizing HTML5 Games: 10 Years of Learnings
Top Content
PlayCanvas is an open-source game engine used by game developers worldwide. Optimization is crucial for HTML5 games, focusing on load times and frame rate. Texture and mesh optimization can significantly reduce download sizes. GLTF and GLB formats offer smaller file sizes and faster parsing times. Compressing game resources and using efficient file formats can improve load times. Framerate optimization and resolution scaling are important for better performance. Managing draw calls and using batching techniques can optimize performance. Browser DevTools, such as Chrome and Firefox, are useful for debugging and profiling. Detecting device performance and optimizing based on specific devices can improve game performance. Apple is making progress with WebGPU implementation. HTML5 games can be shipped to the App Store using Cordova.
Building Fun Experiments with WebXR & Babylon.js
JS GameDev Summit 2022JS GameDev Summit 2022
33 min
Building Fun Experiments with WebXR & Babylon.js
Top Content
This Talk explores the use of Babylon.js and WebXR to create immersive VR and AR experiences on the web. It showcases various demos, including transforming a 2D game into a 3D and VR experience, VR music composition, AR demos, and exploring a virtual museum. The speaker emphasizes the potential of web development in the metaverse and mentions the use of WebXR in Microsoft products. The limitations of WebXR on Safari iOS are discussed, along with the simplicity and features of Babylon.js. Contact information is provided for further inquiries.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
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 🤐)
Make a Game With PlayCanvas in 2 Hours
JSNation 2023JSNation 2023
116 min
Make a Game With PlayCanvas in 2 Hours
Top Content
Featured WorkshopFree
Steven Yau
Steven Yau
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.
Building WebApps That Light Up the Internet with QwikCity
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Miško Hevery
Miško Hevery
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.
How to make amazing generative art with simple JavaScript code
JS GameDev Summit 2022JS GameDev Summit 2022
165 min
How to make amazing generative art with simple JavaScript code
Top Content
WorkshopFree
Frank Force
Frank Force
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.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- 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
PlayCanvas End-to-End : the quick version
JS GameDev Summit 2022JS GameDev Summit 2022
121 min
PlayCanvas End-to-End : the quick version
Top Content
WorkshopFree
João Ruschel
João Ruschel
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.