r/AskProgramming • • 16d ago

Understanding struct of arrays while using a Data-Oriented Design.

Hi!

I'm developing a video game with C++ and Unreal Engine.

A few days ago, I've read and watch some videos about Data-Oriented Design. After that, I've been thinking about how to improve my code and learn how to do it.

To test it, I have declared this struct:

struct MyStruct
{
  TArray<FTransform> Transforms;
  TArray<FVector> Colors;
  TArray<int32> IDs;
  TArray<bool> Visible;
  TArray<FName> Names;
};

This is a structure of arrays, where each Array contains a different data type.

My question is that I'm not sure if that's a good design in the context of data-driven design.

Perhaps the optimisation would come from using arrays of the same data type, rather than using a structure containing data of different sizes as the data type of an array.

Thanks!

0 Upvotes

21 comments sorted by

View all comments

1

u/thatdevilyouknow 15d ago

For gaming I would think that FlatBuffers would be the data oriented approach considering that the Data Oriented Programming book itself references typed JSON and FlatBuffers is equivalent to that but more performance oriented specifically for gaming. It is also possible to implement outside of just downloading the package itself because the same principles still apply. So an example IDL file would look like this. I haven’t watched any videos on this though I’ve just read the book.

1

u/VansFannel 15d ago

I'm not asking about what I'm doing with Unreal. I only mentioned Unreal because the structure uses a data type specific to the engine: FTransform.

My question is: I don't see the benefit of optimizing a structure of arrays if each array is of a different data type.

1

u/thatdevilyouknow 15d ago

The way this is optimized is by aligning the memory because structs when serialized can be accessed by offset. FlatBuffers contains all the alignment information and vtables for accessors. If you are doing this by hand it becomes type unsafe unless you are very thorough. Data oriented programming is as much about the schema as the data. Schemas self-validate before any operation and normally the data is transformed because it should remain immutable. FlatBuffers keeps this off the heap. You manipulate the data because it should be first class. Optimization comes in the form of less boilerplate and casting gymnastics as well since that is determined up front. This is an example of using it for a UI. Compilers optimize insofar as the information provided and structs can be optimized better when memory layout is predetermined different types or not. You are approaching a tricky subject in C++.