Author Topic: Avoiding the garbage collector with UILabel.text  (Read 3256 times)

smartie

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
Avoiding the garbage collector with UILabel.text
« 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:

  1. stringBuilder.Remove(0, _stringBuilder.Length);
  2. stringBuilder.Append(DistanceCurrentScore);
  3. string textScore = stringBuilder.ToString();
  4. scoreLabelHUD.text = textScore;
  5.  

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?

Nicki

  • Global Moderator
  • Hero Member
  • *****
  • Thank You
  • -Given: 33
  • -Receive: 141
  • Posts: 1,768
    • View Profile
Re: Avoiding the garbage collector with UILabel.text
« Reply #1 on: August 28, 2014, 04:02:40 PM »
Not at this point, to the best of my knowledge.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Avoiding the garbage collector with UILabel.text
« Reply #2 on: August 28, 2014, 09:31:13 PM »
Your own code also causes allocations here:
  1. 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().

smartie

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
Re: Avoiding the garbage collector with UILabel.text
« Reply #3 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.


ryan

  • Jr. Member
  • **
  • Thank You
  • -Given: 0
  • -Receive: 1
  • Posts: 90
    • View Profile
Re: Avoiding the garbage collector with UILabel.text
« Reply #4 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...

smartie

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
Re: Avoiding the garbage collector with UILabel.text
« Reply #5 on: September 01, 2014, 04:10:41 AM »
I hope you're at least checking whether DistanceCurrentScore has changed before doing any of that StringBuilder stuff...

yep the design of the game means that score changes every frame.