TArray save length or call Num many times?

Quick optimization question - if I have a TArray that rarely changes size, but the size of the array is referenced very frequently, is it better to store the length of the array in a separate integer variable or call the Num() function very frequently?

I’m not sure whats going on internally in the Num() function. Does Num() just return a integer value saved somewhere memory? Or is it doing some computation to get the return value?

To give a code example - is the usage of Num() here bad practice or should I not worry about it:

UPROPERTY()
TArray<UPerson*> Population;

// ...

bool UResourceSimulator::SimulateFrequentGlobalEvents() {
	if (Population.Num() == 0) {
		return false;
	}

	FoodStock -= Population.Num();
	WaterStock -= Population.Num();

	UE_LOG(LogSS, Log, TEXT("applying global event | Food: -%d, Water -%d"), Population.Num(), Population.Num());

	return true;
}

Just call num :slight_smile:

1 Like

Population itself sounds more like a:
int32 Population;

Unless you have something special in the array like a “person” struct or something it sounds odd.
But again .Num() is just fine.

1 Like

Ah I see, so I were to store the length it would be redundant b/c thats what TArray does internally