unity stringbuilder.tostring()会导致分配堆内存吗?

发布于 2025-02-07 08:55:24 字数 376 浏览 0 评论 0原文

今天,我听说.toString()引起了调用 gc

而且我发现有StringBuilder,所以我决定使用它。

但是,StringBuilder不适合文本,

因此我知道我必须再次使用.toString()

public Text timer;
StringBuilder sb;

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

假设SB已经有什么 此.toString()是否会导致新的堆内存?

如果有人详细给我答案,我将非常感谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幻想少年梦 2025-02-14 08:55:24

正如@zambari在注释中提到的那样,stringBuilder允许仅创建一个为几个串联的结果字符串。但是,每个.toString()调用将导致分配。

首先,没有简单的方法(或者至少我不知道:d)在Unity3d =中制作零分配的视觉计时器),

但是,您可以进行简单的内存优化。如果您只需要显示秒(不准确的毫秒),则无需重新创建字符串表示并将其设置为文本标签每个帧。仅当更改秒数时才足以使其成为。

我说的是这样的事情:

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

例如,如果您在现场有大量的计时器,也许不符合您的需求。但是通常,对于大多数游戏来说,这足够了。

另外,您始终可以在“ Unity Profiler”窗口中检查内存分配。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文