4 ms·
Although it's a fair amount of work, you can make it very simple to switch between SoA and AoS by writing a child class for a C++ vector<yourclass> that templat
by ball_of_lint 7y ago
Although it's a fair amount of work, you can make it very simple to switch between SoA and AoS by writing a child class for a C++ vector<yourclass> that templates your original class, but returns values of a child class of yourclass that operates on the SoA data.
With a public-data-heavy class that might run you into a performance problem with allocating the extra unused memory, but you can always pull out the interface as a virtual parent of both to avoid that as well.
I would rarely be afraid of using SoA over AoS if it can lead to significant performance improvements. Done well it can hide all the complexity with some clever use of interfaces and classes.
- typon 7y agoCan you give an example?
- ball_of_lint 7y agoThis is mainly to illustrate the idea; I don't claim any correctness or good performance from this code. (if you do inserts after reading a [] you may invalidate some pointers!) https://pastebin.com/aZWTAL2J https://pastebin.com/aZWTAL2J impl_X is your base class with most of your logic. interface is used to pull out just the parts of the data that you might work with while wanting to have it in SoA format. Then we specialize the vector template for the interface to give us a dummy class with the things we need, but that sends our writes back to the backing array. If we need to get an individual struct out of it the conversion is automatic. If we just need to access some member vars it will (hopefully) optimize down to direct accesses. We do bear some complexity in implementation, but it's all confined here. I'm now realizing I was a bit imprecise in my earlier comment. the specialized vector is not around <yourclass> but around an interface parent of your class. You could also just specialize yourclass vector, but then you don't have the ability to switch.
- ball_of_lint 7y agoAfter writing that up, I saw below that someone else has done it much like I had envisioned and ironed out the odd parts. Better source: https://github.com/crosetto/SoAvsAoS https://github.com/crosetto/SoAvsAoS
- typon 7y agoThank you
- gpderetta 7y agovery simple minimally intrusive SOA/AOS conversion using templates: https://godbolt.org/z/rBeWOA https://godbolt.org/z/rBeWOA I just typed it in, I'm sure there are errors. I borrowed to_tuple from somewhere, that's the real hack. Real reflection can't arrive too soon. edit: added soa2aos example