Hello, there are various places on the internet where it’s suggested that TMP_Text.SetText is allocation free, but testing it in the Editor definitely allocates. I read somewhre non-official that that’s just because of the Editor, so I built the game and there’s still allocations therethere’s indeed no allocations there.
The strange part is I cannot find a single official statement on this. Is this alloc-free or not? In the UGUI’s package changelog there’s numerous mentions of SetText’s allocation issues fixed, and that’s as official an statement I found on this.
Can someone please clarify whether TMP_Text.SetText allocates or not? For reference, let’s assume the latest Unity LTS and the latest UGUI package.
Hello, I realized my in-build was flawed as I had forgot to assign the text field in the building scene. Once I did that, the built test became allocation-free. What you said would occur when we access the .text property which returns an string, but SetText in itself does not seem to allocate in a build; however I still haven’t found any official statement on this, just that in the package source there’s a line in the SetText that reads:
but without an official documentation backing this up, who knows if this will stay like this in the next build? So I keep my post up in hopes that we’ll get an official reply, but yeah no allocs in build at this point in time.
That is the correct view. If something isn’t documented to be a certain way, don’t count on it.
The .text property has had various grievous leaks in the past, such as one where it produced a stranded Mesh object every time you wrote to it, so it’s just something to keep an eye on whenever you change Unity versions, which should ONLY be done as necessary, not “just because.”
It would likely not differ from passing in $"Hello{number++}" since the string is used on the C# side so it can’t be done exclusively with C++ string formatting.
Note that this is a micro-optimization for many platforms. Even on mobile you can get away with string interpolation every frame if it’s used judiciously.
Since we’ll have to print strings in the UI in some form or another there will always be garbage created when updating the UI. The problem space shifts towards updating the UI intelligently ie only when a value actually changes or rate-limiting the UI update to perhaps every 10th frame - the user won’t notice and it saves you 9 allocations.
On desktop you can let it fly, the UI’s GC allocs are hardly a concern. Mobile or web I’d take a little extra care.
Thanks for the answer as always. All good points.
I’d like to just correct that it was not in fact making allocations, as it turns out; I edited my post to clarity that in builds, TMP_Text.SetText is not allocating, but it’s not documented eitherway, so it might differ from version to version.