简体   繁体   中英

Unity Does StringBuilder.ToString() cause the heap memory allocating?

Today, I heard that .ToString() causes to call GC .

And I have found there is StringBuilder, so I decided to use it.

However, the StringBuilder doesn't fit to text,

so I got to know that I had to use .ToString() again.

public Text timer;
StringBuilder sb;

void Update()    
{
     timer.text = sb.tostring()
}

Assuming what's already in the sb, does this .ToString() cause new heap memory allcating?

I'd really appreciate it if someone gives me an answer in detail.

As @zambari mentioned in the comment, StringBuilder allows to create only one resulting string for several concatenations. But still, every .ToString() call will result in allocation.

First of all, there is no easy way (or at least I don't know it :D ) to make a zero-allocation visual timer in Unity3d =)

But, you can do easy memory optimization. If you only need to show seconds (not accurate milliseconds), you have no need to recreate the string representation and set it to a text label every frame. It is enough to make it only when the number of seconds is changed.

I'm talking about something like this:

    void Update()
    {
        _elapsed += Time.deltaTime;
        int secondsToShow = (int)_elapsed;
        if (secondsToShow != _prevShownSeconds)
        {
            _prevShownSeconds = secondsToShow;
            _timer.text = secondsToShow.ToString();
        }
    }

Perhaps it will not fit your needs if you, for example, have tons of timers on the scene. But usually, it is enough for most games.

Also, you can always check memory allocations in the unity profiler window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM