unity stringbuilder.tostring()会导致分配堆内存吗?
今天,我听说.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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如@zambari在注释中提到的那样,
stringBuilder
允许仅创建一个为几个串联的结果字符串。但是,每个.toString()
调用将导致分配。首先,没有简单的方法(或者至少我不知道:d)在Unity3d =中制作零分配的视觉计时器),
但是,您可以进行简单的内存优化。如果您只需要显示秒(不准确的毫秒),则无需重新创建字符串表示并将其设置为文本标签每个帧。仅当更改秒数时才足以使其成为。
我说的是这样的事情:
例如,如果您在现场有大量的计时器,也许不符合您的需求。但是通常,对于大多数游戏来说,这足够了。
另外,您始终可以在“ 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:
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.