Search Unity

UGUI Text and char arrays

Discussion in 'UGUI & TextMesh Pro' started by PhobicGunner, Oct 15, 2014.

  1. PhobicGunner

    PhobicGunner

    Joined:
    Jun 28, 2011
    Posts:
    1,813
    I'd like to throw this suggestion out there and hopefully get some thoughts on this.

    One of the most insidious sources of garbage for games comes from string manipulation, as strings are immutable. It's incredibly hard (actually nigh on impossible) to completely eliminate this garbage.

    A workaround I've seen is to grab the internal string from StringBuilder (this works because the String class is only immutable outside the System namespace - it's actually mutable inside the System namespace).

    However, this changes in later versions of .NET, as the internal string was refactored to be a char array. So if Unity is going to be updating Mono to newer versions, this workaround will disappear and we're left in the same old boat.

    You might be saying to yourself "Well, then clearly the answer is not to create so many strings". That, of course, is easier said than done (and in some cases, simply not possible).

    Therefore, I'd like to propose that UGUI's Text widget allow us to optionally use char arrays, rather than just strings. By doing so, we could come up with our own StringBuilder-like implementations which internally use a fixed-size char array. This char array could then be passed directly to the Text widget, and in the end no garbage is generated whatsoever.
    It could perhaps be implemented as a flag, for instance Text.useCharArray. And then, when the contents of the char array change, perhaps some sort of Invalidate method to force the Text to redraw.

    It might seem an odd choice, but I feel decisions like this are important for Unity to make, because as developers we need more options for optimizing our games and maintaining high performance in our games.
     
    PrimalCoder and TakuanDaikon like this.
  2. Stephan-B

    Stephan-B

    Joined:
    Feb 23, 2011
    Posts:
    2,269
    I agree.

    Interestingly one of the ways to provide text to TextMeshPro is TextMeshPro.SetCharArray() which does exactly what you request.

    The 3 ways to provide text input to TextMesh Pro are:
    TextMeshPro.text
    TextMeshPro.SetText
    TextMeshPro.SetCharArray


    The SetText() and SetCharArray() are both GC free.

    P.S. Personally, I wish we had a way to budget how much time per frame the Garbage Collector is given to handle the GC process. This would enable us to using strings and do new allocations without having to jump through so many hoops to avoid GC. Obviously, if more GC Alloc is created per frame than what can be handled in the budgeted time, you would ultimately run into trouble but that would be much easier to manage then having to completely try to avoid all GC like the plague.