Hi, what is the best practice with TObjectPtr
and TWeakObjectPtr
? From what I have seen so far, TWeakObjectPtr
is usually dereferenced before using it, especially in a loop, to avoid multiple dereferencing, which could be costly. However, I performed a small benchmark and it turned out that dereferencing TObjectPtr
is more costly than dereferencing TWeakObjectPtr
. I can also say that I have never seen TObjectPtr
dereferenced before using it
first loop : TWeakObjectPtr : 62s , TObjectPtr : 79s.
second loop : 41s.
{
TWeakObjectPtr<AActor> WeakActor = GetOwner(); /*TObjectPtr<AActor> WeakActor = GetOwner();*/
const int64 NumIterations = 10000000000;
{
const double Start = FPlatformTime::Seconds();
for(int64 i = 0; i < NumIterations; ++i)
{
WeakActor->SetActorTickEnabled(false);
}
const double Duration = FPlatformTime::Seconds() - Start;
UE_LOG(LogTemp, Warning, TEXT("Dereference every time obj: %f s"), Duration);
}
{
const double Start = FPlatformTime::Seconds();
AActor* RawActor = WeakActor.Get();
for(int64 i = 0; i < NumIterations; ++i)
{
RawActor->SetActorTickEnabled(false);
}
const double Duration = FPlatformTime::Seconds() - Start;
UE_LOG(LogTemp, Warning, TEXT("One Get() then use raw: %f s"), Duration);
}