r/AskProgramming • • 15d 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/csiz 15d ago

It's a more cumbersome way to store values, but it has performance benefits if you're doing lots of maths with those numbers. And especially if that maths works on subsets of properties at a time. The benefit comes from accessing a more compact representation in memory so if you're doing let's say something with position then it's faster to have an array with just the positions.

Wouldn't recommend it if you don't have a good reason for it though, it's significantly more cumbersome and also costly to insert elements in the middle.

-1

u/VansFannel 15d ago

And regarding what I asked, do you have an answer?

2

u/BobbyThrowaway6969 15d ago

If you were rolling your own high efficiency app, sure, but as you're using Unreal, just go with their recommendations since they've built the engine around them

Struct of arrays is to get good cache optimisation but it's a drop in the bucket when you're fighting against the rest of the engine.

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.

2

u/BobbyThrowaway6969 15d ago

If the arrays were of the same data type then that would just be a 2D array.

The struct of arrays IS the optimisation, for CPU caching. But if you're not aiming for that then there's basically no value to doing structs of arrays, apart from mass copying, data representation and serialisation.