A Performance Investigation of UnityEngine.UI That Began with "Doesn't Rich Text Add a Crazy Number of Vertices?"
When you make UI in Unity, UnityEngine.UI is the first thing you reach for.
It's a great help, since you don't have to think about the internals: just drop in Images and Texts and it works. But every now and then it suddenly gets terribly slow.
In this article, I, Hirayama from the Technology Department, write about something I stumbled upon, and everything I looked into about UnityEngine.UI's performance once it had made me curious.
For those in a hurry, here are the conclusions as bullet points.
- Touching Graphic.color, RectTransform.sizeDelta or Text.text is slow
- Just moving things isn't very slow, but it's slower than not moving them
- Rich text is slow
If you're curious, read on.
The Unity version is 2017.4.8f1. Plenty of this may well be improved in 2018, but please bear with me on that.
The UI profiler is handy! Or so I thought...
The UI profiler arrived in Unity 2017. It's very handy, showing how many vertices and how many DrawCalls each Canvas has. And in it, I found something strange.

Isn't that a lot of vertices?
It says 720 vertices, but all this is displaying is one character.

A character is 4 vertices, 6 indices and 2 triangles, at least if you do it the normal way. And that becomes 720?
Then it dawned on me. "Oh, it's because of Outline." It has an outline, after all.
Outline draws the character shifted in several directions, so the vertex count multiplies. That must be it. I tried removing it.

There are still 96 vertices. What's going on? At this point, I took another look at the string I'd put into the Text.
<color=#ff0000>赤</color>
It uses rich text. Only one character, 赤 ("red"), is displayed, but counting the characters including the rich text
tags, there were 24.
96 vertices divided by 4 is 24.
...It's generating vertices for the rich text tags too, isn't it? Seriously?
If it's not heavy I don't care, but is it?
So we know there are oddly many vertices, but this is probably the kind of problem that goes away with a newer Unity. And if it doesn't actually make things slower, we can just leave it alone.
So I decided to measure whether it makes things slower. I'll compare the load with Outline enabled and disabled.
The measurements were made in the editor on a MacBook Pro Mid 2014 (i7 3GHz).
public class Sample : MonoBehaviour
{
public Text textPrefab;
public Canvas canvas;
Text[] _texts;
const int N = 100;
int _frame;
void Start()
{
_texts = new Text[N];
for (int i = 0; i < N; i++)
{
_texts[i] = Instantiate(textPrefab, canvas.gameObject.transform, false);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.F1))
{
foreach (var text in _texts)
{
var outline = text.gameObject.GetComponent<Outline>();
outline.enabled = !outline.enabled;
}
}
var str = _frame.ToString("D5");
foreach (var text in _texts)
{
text.text = str;
}
_frame++;
}
}
A Text with an Outline is made into a prefab, and Start() instantiates 100 of them. Their parent is the canvas.
In Update(), when F1 is pressed it gets the Outline component and toggles enabled, and every frame it increments
_frame, turns it into a string and sets it on the Texts. I didn't want the number of characters to change partway,
so I passed "D5" to ToString to fix it at 5 digits.
Let's run it.

Sickeningly slow!
Purple is the UI load. It must be generating vertices. This UI processing is eating about 20 ms. This is with Outline, and the vertex count is 15000.
Now let's press F1 and turn off Outline.

It got massively faster. About four times faster. The cliff in the graph is when I switched. The vertex count is now 2000.
It seems that even vertices that come from rich text tags slow down the processing. That's a problem.
How many times does Outline multiply the vertices? And why?
Before thinking about countermeasures, let's check how many times the vertex count is multiplied when you add Outline.
From the results above, it's 15000 with Outline and 2000 without, so it's multiplied by 7.5. What's going on there?
First, the vertex count without Outline is 2000, and there are 100 Texts of 5 characters each, so that's 4 vertices per character.
With Outline, that goes up to 30 vertices per character. 30 factors into 2×3×5, so there must be a factor of "5" somewhere. It's probably drawing it 5 times. Perhaps shifted up, down, left and right in black, then once in the middle in the proper color. If so, that's 6 vertices per draw, which works out to an increase of about 1.5 times. More on this later.
So how do we reduce them?
One option is making your own Outline that draws fewer times. But of course it looks worse. In fact, in our game Tokyo Prison, we use a simplified version that draws only one extra time in some places, but it compromises on quality.
The other option is somehow getting rid of the vertices that come from the rich text tags. That should make it faster even without Outline, so if it can be done, it's a win. Let's try that next.
BaseMeshEffect
The official docs describe how to modify the vertices a Graphic has. You make a component that inherits from a class called BaseMeshEffect, and implement ModifyMesh().
However, as of November 29, 2018, the ModifyMesh that takes a Mesh as its argument is obsolete, and that isn't mentioned anywhere. The version that takes a VertexHelper seems to be the official one. It's probably not used much, so they haven't updated the manual. That happens a lot with Unity, so I'll use it without worrying.
public class DegenerateQuadRemover : BaseMeshEffect
{
private static List<UIVertex> _verticesCache; // reused
static DegenerateQuadRemover()
{
_verticesCache = new List<UIVertex>();
}
public override void ModifyMesh(VertexHelper vh)
{
vh.GetUIVertexStream(_verticesCache);
// TOOD: do something here
vh.Clear();
vh.AddUIVertexTriangleStream(_verticesCache);
}
}
I named it Degenerate Quad Remover, meaning "the one that removes quads with zero area". If there are
vertices but they can't be seen, either they're at coordinates at the edge of the universe and don't show on screen,
or their area is zero. I dumped all the vertices with Debug.Log to check, and it was the latter. So we handle the
zero-area case.
We get the current vertices from the VertexHelper we're given. When there are several components attached, they're processed from top to bottom (though I haven't found any document guaranteeing this...), so if this component is attached below the Text, we get the vertices generated by the Text. I don't want to new this array every time, so I create it in a static constructor and reuse it.
Then we do something where it says TODO:, and once the data is ready, call
VertexHelper.Clear() and set the new vertex
array with
VertexHelper.AddUIVertexTriangleStream().
If I could modify the original array in place and just shrink it by the number of vertices no longer needed, there'd be no extra copying and it wouldn't eat memory, but I couldn't find a way to do that. If you find one, please tell me.
Now let's write the body.
public static void Process(List<UIVertex> vertices)
{
int letterCount = vertices.Count / 6;
Debug.Assert((letterCount * 6) == vertices.Count); // if the vertex count isn't divisible by 6, the assumption is broken
int srcVertexIndex = 0;
int dstVertexIndex = 0;
for (int letterIndex = 0; letterIndex < letterCount; letterIndex++)
{
vertices[dstVertexIndex + 0] = vertices[srcVertexIndex + 0];
vertices[dstVertexIndex + 1] = vertices[srcVertexIndex + 1];
vertices[dstVertexIndex + 2] = vertices[srcVertexIndex + 2];
vertices[dstVertexIndex + 3] = vertices[srcVertexIndex + 3];
vertices[dstVertexIndex + 4] = vertices[srcVertexIndex + 4];
vertices[dstVertexIndex + 5] = vertices[srcVertexIndex + 5];
var p0 = vertices[dstVertexIndex + 0].position;
var p1 = vertices[dstVertexIndex + 1].position;
var dx = p1.x - p0.x;
var dy = p1.y - p0.y;
if (((dx * dx) + (dy * dy)) > 0f)
{
dstVertexIndex += 6;
}
srcVertexIndex += 6;
}
vertices.RemoveRange(dstVertexIndex, vertices.Count - dstVertexIndex);
Debug.Assert(vertices.Count == dstVertexIndex);
}
GetUIVertexStream gives you the vertex array, but with 6 vertices per character. You don't get an index buffer, and if you're doing it with just a vertex buffer, you have no choice but to duplicate 2 vertices to make 6. That's probably why it was 6 vertices per character with Outline enabled.
Now for the heart of the processing. It loops one character at a time, copying it to the new array if it has area and skipping it if the area is 0. That said, calculating the area properly would mean looking at all 6 vertices, which is slow, so here I only look at 2 vertices per character. For the vertices that come from rich text tags, the first and second vertices have the same coordinates, so the sum of the squared differences in x and y is 0. position is a Vector3, but there's no need to look at z. This depends entirely on how Text generates vertices in the current version, so it may stop working if the Unity version changes. If that worries you, you'd be better off implementing it more properly.
Slot this Process into the place where it said TODO: earlier and it's done. Then attach this component.

The order matters. It has to be below the Text and above the Outline. That way it cuts the Outline's processing load too.
Measuring again
Now let's measure. This time I use a string that includes rich text tags, and compare with and without DegenerateQuadRemover attached.
var str = "<color=#ff0000>" + _frame.ToString("D5") + "</color>";
I changed the string generation like this and measured.


The left is without vertex removal. There are 84000 vertices and the graph is completely purple. The right is with vertex removal, and the vertex count is 15000. The graph has improved a lot. This confirms that removing the extra vertices, at an acceptable processing cost, lowers the processing load further down the line.
But even after that drop, it's over 30 ms. Before switching to rich text it was about 20 ms, so that must be how heavy rich text is. If it outputs vertices for the tags, then presumably all the font-texture processing and so on for the tag characters is running too, which is pure waste. Being able to produce a string with different colors and sizes in different parts within one Text is handy, but if the format is fixed, you may be better off splitting it into several Texts. For example, in a case like
<color=#ffffff>レベル:</color><color=#ff88cc>25</color>
if you split the "Level:" label (レベル:) and the number, there's less to update, and you don't need rich text tags
either.
Isn't changing strings every frame the problem in the first place?
As you may have noticed, the root of all evil is the very act of setting a different string on lots of Texts every frame. UnityEngine.UI probably wasn't designed for that. That's why it gets ridiculously heavy.
In Tokyo Prison, some of the things that change every frame are numbers. Like the 4-digit number beside the hit point gauge.

For presentation reasons, when it goes down from 2500 to 1900, for example, it whirs down over several frames. Instead of jumping straight to 1900, it changes 2499, 2498, 2497... and so on. Doing this with Text makes for an awful load. You need some kind of workaround.
In Tokyo Prison, we get around this problem by placing one Image per digit and swapping the digit sprites individually.
But be careful: calling SetNativeSize() when you swap the image makes it shockingly slow. If you do things like making
just the 1 narrower, it gets awful. You either have to make every digit the same width and give up on looks, or keep
the image size the same and adjust the positions yourself.
Is it true that moving things makes them slow?
People say all sorts of things about UnityEngine.UI along the lines of "do this and it gets slow". But to be honest, while making the product we never found the time to check properly. So while I'm at it, I'll take the time now.
According to the official documentation, when UI gets slow, it's down to things like
- the GPU bottlenecking on filling pixels
- the CPU bottlenecking on rearranging the draw order to cut DrawCalls
- the CPU bottlenecking on generating vertices (mainly for strings)
Let's not worry about the GPU for now. In my experience, with cheap smartphones, it's usually the CPU that's the bottleneck. Even if the GPU does become the bottleneck, you can ease it by lowering the resolution, so in a sense it's not serious. In Tokyo Prison too, the standard resolution is set on the low side (1136x640), and a few tricks cut the fill area itself considerably (for example, "drawing frames dynamically").
So the problem is the latter two. Let's test those.
First, let me list things that look like they'd be heavy.
- Changing Text.text (we've already seen this)
- Instantiate/SetParent
- Changing Graphic.color
- CanvasRenderer.SetColor
- CanvasRenderer.SetAlpha
- Changing anchoredPosition
- Changing localRotation
- Changing localScale
- Changing sizeDelta
To start with, changing a string obviously triggers vertex generation, which you want to avoid as much as possible while the game is running at 30 FPS or 60 FPS. A large part of it will be numbers, so avoid it with the trick above, and for the remaining strings, generating them in advance and caching them seems like a good idea. Likewise, when Instantiate creates something new under the Canvas, vertex generation should run, so I expect it to be the same kind of load you should avoid. The same probably goes for switching parents with SetParent.
Next, color. If you want to animate transparency, touching Graphic.color every frame is the straightforward way. I'd hate for that to be slow, so let's measure it. You can do similar things with CanvasRenderer.SetColor() and CanvasRenderer.SetAlpha(), so let's compare those too.
The rest will probably affect the processing that rearranges the draw order.
Say there are two textures, A and B, with two Images, A1 and A2, using A and two Images, B1 and B2, using B. If the order in the Hierarchy is A1, B1, A2, B2, then without any cleverness there are 4 DrawCalls. It needs to set a texture 4 times, and that can't be changed.
But if B1 and A2 don't overlap, drawing in the order A1, A2, B1, B2 gives the same result. In that case, the texture only needs to be set twice, and the DrawCalls can be reduced to 2. To do this, you need to check "do A2 and B1 overlap?" It presumably calculates the on-screen bounds of each RectTransform and tests for overlap. Changing anchoredPosition, localRotation, localScale or sizeDelta requires that overlap test to be redone. I don't think you'd change them dynamically much, but anchorMin, anchorMax, pivot and so on are probably the same.
Preparing the measurement
First, if there are only 100 Texts, there's only 1 DrawCall to begin with, so there's no need to reorder anything. So I made 50 of the 100 into Images and generated them alternately.

If they all overlap in the center of the screen, there are 100 DrawCalls.
Then I prepared lots of bool switches so that actions like changing the color, changing the position and rotating can be turned on and off.

Try changing anchoredPosition every frame and it looks like this:

If you look at the Rendering part of the profiler, the number of DrawCalls fluctuates every frame. That's proof that Unity is working hard at reordering. There are 29 DrawCalls for drawing the UI, so it was originally 129, but moving the positions randomly brings it to around 85. You can see it's aggressively reordering wherever things don't overlap.
Measurement
Now let's measure. I made the settings changeable from the UI, so I can measure with a build rather than the editor. Right now I want to know "what makes it heavy" rather than "how heavy it actually is", so I feel the editor would be enough, but if I put numbers out in an article like this, I'll probably get told "the editor is inaccurate, so the data can't be trusted", so I'll look at a build. I make a standalone build for macOS, connect to it from the profiler, and look at the numbers while changing settings.
On to the measurement. For now, let's not worry about the load from DrawCalls (Rendering in the graph) and just look at how heavy the UI gets. I'll eyeball the thickness of the purple UI graph and call it "about this much".
| Text.text | Graphic.color | CanvasRenderer.SetColor | CanvasRenderer.SetAlpha | |
|---|---|---|---|---|
| Just one | 0.2ms | 0.2ms | 0.02ms | 0.02ms |
| All | 4ms | 5ms | 0.04ms | 0.04ms |
| anchoredPosition | localRotation | localScale | sizeDelta | |
|---|---|---|---|---|
| Just one | 0.03ms | 0.03ms | 0.03ms | 0.2ms |
| All | 0.11ms | 0.11ms | 0.11ms | 5ms |
With nothing being changed, it's about 0.01 ms.
"Just one" and "All" mean "touch only the first Text" and "touch all the Texts/Images" respectively ("All" if SetAll in the GUI is true, "Just one" if it's false). For the reordering, even touching just one should have a wide impact, so I looked at how much. The results are roughly:
- Changing the string, Graphic.color or sizeDelta is horrendously heavy. It looks as if it's redoing everything, starting from vertex generation.
- Changing position, rotation or scale makes it heavier, but not so heavy that I'd want to split canvases or anything.
- In every case, changing just one doesn't mean everything gets redone, but it doesn't cost just 1/100 either.
From this, my personal take is:
- "Put moving things and non-moving things on separate Canvases" seems to have little effect for the effort.
- Whatever you do, don't touch sizeDelta or Graphic.color.
- I don't much feel like using components that adjust width/height automatically.
- I suspect the hopeless slowness when I called SetNativeSize() every frame was the same thing.
- Change colors through CanvasRenderer. If you're changing alpha for a group, maybe CanvasGroup.
It was quite a shock that just touching the sizeDelta of a single Text takes 0.2 ms. And this was measured on a PC; on a smartphone I'd expect it to be several times slower.
Summary
"UnityEngine.UI is slow when you move things" isn't wrong, but I feel it's a little inaccurate. If you're just animating position, rotation and scale, I don't think it matters that much unless you have a really large number of vertices and objects. I don't know whether it was always like that or got faster recently.
I also thought the load might vary with the number of materials in the canvas, so I compared using just 1 image with using 19, but I couldn't see a difference. I get the feeling that having many materials, shaders and textures doesn't change the load. In a product, you'd atlas the textures to cut the number of DrawCalls as much as possible, so the problem gets even smaller.
However, for three things, Text.text, Graphic.color and sizeDelta, I was able to confirm that the load could immediately lead to dropped frames. These are probably rebuilding the vertices, and the load is in a different league. SetNativeSize() changes sizeDelta, so it should be avoided too, and the same thing happens if a HorizontalLayoutGroup is adjusting positions every frame. I'd expect the load to be proportional to the vertex count, so an Image with few vertices may be fine, but from our experience with Tokyo Prison, I feel it's better to avoid changing sizeDelta every frame even on a plain Image (though the Unity version back then was 5.6). Do transparency animation with CanvasGroup or CanvasRenderer. With CanvasRenderer you can also multiply the color.
Finally, though it's minor compared with what the later measurements turned up, rich text is currently slow because it generates vertices needlessly. The component I introduced here may help lighten it a little. Then again, if Unity fixes the implementation that won't be necessary, and it's only noticeably heavy when generating vertices. Not worrying about it is also an option, I think.
I've put all the sample code on GitHub. DegenerateQuadRemover is included too. While I was at it, I've also put up a WebGL build. Take a look if you want to get a feel for the program used for the measurements.