Search code examples
performancevectorstructsharpdx

Wrapping a Vector class around the SharpDX Vector struct - Performance?


I have some issues with using the Vector3 class as wanted, mostly because it is a struct and additionally because it doesn't raise something like an event when a component has been changed.

Eventually, I want to be able to write _camera.Position.Z += 0.1f;

This is not possible with the SharpDX.Vector3 because it is a struct and I cannot modify its components (since a copy is returned when calling _camera.Position).

Also, there's no event like ComponentsChanged on which I would update my camera view matrix for example.

I decided to create a wrapper class around the Vector3 struct, which also provides such an event. Since calling _camera.Position returns me a reference then, I can also modify the Z component directly.

However, I have doubts if this is a good idea for performance reasons.

  • Is it really good to move a Vector3 into a class?
  • Is it bad to raise an event every time a Vector3 component has changed (even if there are no / one / less subscribers)?

Solution

  • Using structs for storing vectors is the right format as it is much more efficient in space and maps directly to the native format expected/returned by the underlying C++ API.

    Hence it is bad and uncommon to raise an event on each component changes on a struct. Structs are lightweight datas, space efficient and in the case of D3D, used for native interop. Events are usually raised on the class holding the value type (e.g camera component). This is a recommendation valid in general in .NET and used extensively throughout the .NET framework