Search Unity

TextMeshPro TMPro_ExtensionMethods ArrayToString question

Discussion in 'UGUI & TextMesh Pro' started by ExNinja, Jun 22, 2020.

  1. ExNinja

    ExNinja

    Joined:
    Dec 4, 2013
    Posts:
    30
    Hello,

    I looked and didn't find any information about this elsewhere in the forums. While working on my own extension methods and also reducing garbage creation, I came across this extension method for strings in the TextMeshPro file TMPro_ExtensionMethods:

    Code (CSharp):
    1. namespace TMPro
    2. {
    3.     public static class TMPro_ExtensionMethods
    4.     {
    5.  
    6.         public static string ArrayToString(this char[] chars)
    7.         {
    8.             string s = string.Empty;
    9.  
    10.             for (int i = 0; i < chars.Length && chars[i] != 0; i++)
    11.             {
    12.                 s += chars[i];
    13.             }
    14.  
    15.             return s;
    16.         }
    17.     }
    18. }
    This probably isn't used much in TMPro, but if it is, it's my understanding that using += on strings causes a ton of additional garbage to need to be collected (I was using "Loading "+"."+"."+"." somewhere and was shocked by how much garbage it generated). I think that this extension method has been in TextMeshPro since 2015.

    So, my question is twofold:
    1. Would converting this to either string s = new string(chars); or using System.Text.StringBuilder() be more efficient from a memory standpoint?
    2. If I made this change to my personal copy of TextMeshPro, would it break anything?