How to automatically convert from Array of Classes to Class of Arrays

algorithm, arrays, class, java, performance

Solution

Let's create an interface that exhibits the first layout for usage, and an implementation for that interface that uses the second layout internally. (Access modifiers stripped from the code.)

interface X {
    double getA();
    double getB();
    double getC();
};

interface ArrayOfX {
    X get(int index);
};

class ContiguousArrayOfX implements ArrayOfX {
    class ContiguousX implements X {
        int index;
        ContiguousX(int index) {
            this.index = index; }
        double getA() { return a[index]; }
        double getB() { return b[index]; }
        double getC() { return c[index]; }
    }

    X get(int index) {
        return new ContiguousX(index); }

    double a[] = new double [SIZE];
    double b[] = new double [SIZE];
    double c[] = new double [SIZE];
};

If you want to lessen the burden on the GC, you can also cache all instances of `ContiguousX`. It depends pretty much on the aptitude of the JIT compiler if the `ContiguousX` objects are allocated on the heap at all -- they might well live in the stack, in this case the overhead is negligible. As a last resort, you can define an alternative interface for fast access:

interface FasterArrayOfX {
    double getA(int index);
    double getB(int index);
    double getC(int index);
};

class FasterContiguousArrayOfX extends ContiguousArrayOfX implements FasterArrayOfX {
   // Exercise left to the reader
};

By programming against an interface you are always free to choose the storage later on.

It is rather straightforward to write a code generator for any given class layout. The code above can be used as boilerplate, only the method and array declarations are dependent on the class layout you want to obtain. I am not aware of any existing tool.

Problem

I would like to know how (if it is possible) could I program a Java class using a data layout `Array of Class`, for example: ``` public class X{ double a; double b; double c; } public X array_of_x[SIZE] = new X [SIZE]; ``` but internally the data would be store as a layout of `Class of Arrays` like this: ``` public class X{ double a[] = new double [SIZE]; double b[] = new double [SIZE]; double c[] = new double [SIZE]; } public X class_x = new X(); ``` My objective is that the programmer could programed in a more intuitive style like the first one, but internal I would do transformations so the data could be continuous in memory, and I would achieve more performance. Is there any way of doing this so it could accept any class with the first type of struct and be able to convert it to the second approach? (or is any tool that is able to do this type of transformation).

Original source