Call function .Len() or as a member variable

In the lecture you had to write something like:

 PrintLine(TEXT(''... is  %i characters long"), HiddenWord.Len());

 ...

 if (Input.Len() == HiddenWord.Len()) { ... }

but wouldn’t it better to store the result of HiddenWord.Len() into a member variable in the header file? So you don’t have to make function calls everywhere around in your code.

More forward in the course you will have to generate a random hidden word every time the game starts, if you store the result of HiddenWord.Len() into a member variable in the header file, you will not can. In any case, you could store the result of HiddenWord.Len() into the implementation BeginPlay() function, inside the .cpp file and after generating the HiddenWord.

I did it with this:

void UBullCowCartridge::BeginPlay() // When the game starts
{
    Super::BeginPlay();

    SetupGame();
    ...
}

void UBullCowCartridge::SetupGame()
{
    HiddenWord = TEXT("cake");
    Lives = 3;
    HiddenWordLength = HiddenWord.Len();
}

If you store the result into the implementation of BeginPlay() function then it would only available in that function right? So that leaves the function UBullCowCartridge::OnInput which also needs the result.

but it might be a little complex setup.

I did this kind of setup because on every input change then we do calculate the amount of characters everytime and we do know them a step ahead. So I did think if we assign it into the header file then. it only gets calculated ones the HiddenWord has been initialized.

What do you think about it?

It might change in the forward sections but I was just curious about the current situation without the next lectures.

If it’s not a class invariant it probably shouldn’t be a member variable.

Length is an integer on the stack; there’s no performance gain by making it a member variable. In fact doing so is most likely worse as you would prevent it from being optimised away by the compiler as you would now make it part of the class layout so it’s always in memory. Either the entire instance of the class is optimised away or none of it is.

With it being a local variable it would most likely just use a register and not allocate any memory whatsoever.

In any case, FString stores that length information and Len is forced to be inlined which in a nutshell means say FString’s member that stores that is called Length then SomeString.Len() is equivalent to just accesing Length directly instead of a function call.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms