SetComponentData vs AddComponentData

I’ve looked around, and I can’t seem to find an answer as to whether there is a performance difference between these.

I know that SetComponent/SetComponentData will error out if the Component doesn’t already exist, while AddComponent/AddComponentData will overwrite any existing data for the component (without erroring).

Based on this, I would favor always using AddComponent, but is there any performance advantage to using SetComponent if you’re sure that the Component exists?

1 Like

AddComponent data doesn’t set the component data if the component data already exists, it just returns earlier without modifying the component.

So, in short, use AddComponent when the entity doesn’t have the component and SetComponent when it does.

Add component data still sets data if the component exists. You can use it as a safe set.

As for the OP, set is faster because it doesn’t do the add checks, but it’s marginal.

7 Likes

Thanks tertle! I figured it must be faster (otherwise it was pointless), but I couldn’t find any confirmation of that or an explanation of why.

In previous older entities packages, adding component on existing component, throwed an error, if I remember correctly.

1 Like

that was a long time ago now!

2 Likes

Sure, was around year ago, or so.
For developers year is like blink of an eye :slight_smile:

2 Likes

As I know, AddComponent will change of the entity’s archetype and cause memory chunk change. The components data on that entity may move to another memory chunk that meets the same archtype.
SetComponentData will not cause memory change~

1 Like