String.Length vs. (int) string > val ?

I have int values that i want to display in TextMeshPro elements.

I turned off AutoSize on all TMP elements to save performance, so i’ve to pre-calculate the fontSize values depending on the number of characters displayed.

Whenever a value changes in any TMP, i check the character count and i just assign the pre-calculated value as fontSize for that count.

To get the number of characters i’m using this:

private void SetFontSize(string str)
{
        var length = str.Length;
        if(length == 1)
        {
           a.fontSize = oneCharFontSize;
        }
        else if(length == 2)
        {
            a.fontSize = twoCharFontSize;
        }
        else if(intStr == 3)
        {
            a.fontSize = threeCharFontSize;
        }
       else if(intStr == 4)
        {
            a.fontSize = fourCharFontSize;
        }
        .....
}

Is it better this way or should i use:

private void SetFontSize(string str)
{
        int intStr = (int) str;
        a.fontSize = oneCharFontSize;
        if(intStr > 9)
        {
           a.fontSize = twoCharFontSize;
        }
        else if(intStr > 99)
        {
            a.fontSize = threeCharFontSize;
        }
        else if(intStr > 999)
        {
            a.fontSize = fourCharFontSize;
        }
        .....
}

Which one is less expensive if i’m doing this A LOT ?

Why not put all of your precalculated font sizes in an array, and then just do this:

int[] fontSizes;

private void SetFontSize(string str)
{
    var length = str.Length;
    a.fontSize = fontSizes[length - 1];
}

@PraetorBlue
That’s what i’m doing actually i don’t know why i wrote the if else statements, but my question is about the .Length function:
is it expensive to use? should i just cast to int and check if larger than 9 and 99 and 999 respectively?

Keep in mind that i’m doing this like 40 times per second.

Length is not expensive to use. Parsing the string to an int is definitely slower. I don’t think it’s like strlen in C where it traverses the whole string to find a null terminator. Even if it was, parsing would require reading the whole string too and doing a lot more work than just counting the characters.

2 Likes

Well if this is the case then i’ll stay with .Length

Thank you man :slight_smile: