Support => NGUI 3 Support => Topic started by: smartie on August 28, 2014, 11:42:33 AM
Title: Avoiding the garbage collector with UILabel.text
Post by: smartie on August 28, 2014, 11:42:33 AM
Is there any way of setting the text in a UILabel without allocating memory?
We have some code that is setting the current score every frame like this like this:
stringBuilder.Remove(0, _stringBuilder.Length);
stringBuilder.Append(DistanceCurrentScore);
string textScore = stringBuilder.ToString();
scoreLabelHUD.text= textScore;
And this causes memory allocations every frame because UILabel.text is a string, which is immutable, so has to be recreated every time we want it to change.
Is there an alternative way of setting a text value for a UILabel which doesn't allocate memory?
Title: Re: Avoiding the garbage collector with UILabel.text
Post by: Nicki on August 28, 2014, 04:02:40 PM
Not at this point, to the best of my knowledge.
Title: Re: Avoiding the garbage collector with UILabel.text
Post by: ArenMook on August 28, 2014, 09:31:13 PM
Your own code also causes allocations here:
stringBuilder.ToString();
The label actually checks to see if the value changed, and ignores the set operation if it hasn't. My guess is that the majority of your GC allocs come from your string builder / ToString().
Title: Re: Avoiding the garbage collector with UILabel.text
Post by: smartie on August 29, 2014, 04:16:26 AM
yes it's true that ToString() causes allocations but we only need to do that because UILabel.text is an immutable string so we need an allocation to change it. If UILabel.text had an overload that took a char array then we could write directly into that array without any allocation.
Title: Re: Avoiding the garbage collector with UILabel.text
Post by: ryan on August 29, 2014, 11:57:53 AM
I hope you're at least checking whether DistanceCurrentScore has changed before doing any of that StringBuilder stuff...
Title: Re: Avoiding the garbage collector with UILabel.text
Post by: smartie on September 01, 2014, 04:10:41 AM