Delegates vs Interfaces - What is less expensive? (or more efficient)

I wonder which is better. Delegates or interfaces?

This is my use case:

TArray<UActorComponent*> ActorComponents = GetComponentsByInterface( UMyInterface::StaticClass() );

	for (UActorComponent* Component : ActorComponents)
	{			
		if (IMyInterface *MyInterfacePtr =       
            Cast<IMyInterface>(Component))
		{	
			MyInterfacePtr->Function();
		}		
	}

Or

	if (MyEvent.IsBound())
	{
		MyEvent.Broadcast();
	}

Thank You So Much!!

Interfaces are completely different thing than delegates. But I would have to have more UseCase details. Why do you need it? How do you use it? In order to tell you what is better.

If something has to be called for the actor component, I would encapsulate that in the actor itself. There is no need that anyone else should know about it.

2 Likes

I want to handle some events from the actor components To have the code split, clean and tidy. For example GameMode events.

void AMyGameMode::OnPostLogin(AController* NewPlayer)
{
	if (MyOnPostLoginEvent.IsBound())
	{
		MyOnPostLoginEvent.Broadcast(NewPlayer);
	}	
	Super::OnPostLogin(NewPlayer);
}

or

void AMyGameMode::OnPostLogin(AController* NewPlayer)
{
	TArray<UActorComponent*> ActorComponents = GetComponentsByInterface( UMyInterface::StaticClass() );

	for (UActorComponent* Component : ActorComponents)
	{			
		if (IMyInterface *MyInterfacePtr =       
            Cast<IMyInterface>(Component))
		{	
			MyInterfacePtr->OnPostLogin(NewPlayer);
		}		
	}
	Super::OnPostLogin(NewPlayer);
}

For this I want it. In both cases I have the same result.

So if I have to choose one of the two, I would prefer to choose the most efficient one.

It’s true that with interfaces I don’t need to know the type of component and that’s an advantage.

But I wonder in terms of processing cost which is more efficient.

Thanks for your reply!!

In this case, I would definetely go with delegate. It looks more efficient to me. I don’t understand full logic behind your need for this, but looking at what do you want to do, yeah… definetely delegates.

Game mode is ready before the actors, so you should be good to go. But be aware that if you have multiplayer in your game, then you need to use GameState, and it can become available a bit more in the actor lifecycle.

1 Like

The logic is simple. Each component is dedicated to doing a single thing (Clean Code). One gathers the players, another organizes the teams, another spawns the players… It’s a way of having everything divided and well organized.

If it were a blueprint it would be a way to avoid spaghetting XD

I will use delegates.
Thank you very much for your help!!
Very appreciated!! :heart:

1 Like

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