Performance Issues

Could you guys see anything inefficient with this code?

    void UpdateStringText(string message)
    {
        StringBuilder sb = new StringBuilder();

        sb.Clear();

        sb.Append(message);
        sb.ToString();
        text.text = sb.ToString();
    }

    void UpdateTextLanguage()
    {

        if (languageManager.CURRENT_LANGUAGE == languageManager.ENGLISH)
        {
            UpdateStringText(English_Text);
         
            text.fontStyle = FontStyle.Normal;

            text.lineSpacing = englishLineSpacing;

            // sets our font size to our best fit size
            text.fontSize = text.cachedTextGenerator.fontSizeUsedForBestFit;
        }

When this runs my games stutters for like 0.8 seconds. Any ideas?

EDIT: It also appears when this code runs I have a huge spike in CPU Usage.

EDIT: The spikes are specifically to rendering.

I am not sure but that may be text best fit (line 24 in your code). Quick search gave me this forum thread: [NEW GUI]Text "bestfit" Performance Hit
Try to comment this line and see if that fixes the freeze
By the way, are you using the old UI text or TextMeshPro?

old UI.

It’s not the best fit.

UpdateStringText uses StringBuilder unnecessarily and makes performance worse.

You (a) instantiate a new StringBuilder, (b) append only message, (c) instantiate a new string: ToString(), (d) assign to the text. The steps (a), (b), (c) are unnecessary and result in additional garbage generation.

You could simply assign the string to the text: text.text = message;

StringBuilders are useful when you want to concatenate several strings together. They may save performance in that situation.


That inefficiency, however, cannot account for 0.8 sec. There’s something else going on which we’d need to see pics from the Profiler to understand.

Done every frame, this would cause a large amount of pressure on the garbage collector and would be an expected source of stuttering.

At a minimum, you’d want to cache the results and only calculate if something changed.