On Tuesday, 2 January 2018 at 18:21:13 UTC, Tim Hsu wrote:
I am creating Vector3 structure. I use struct to avoid GC. However, struct will be copied when passed as parameter to function


struct Ray {
    Vector3f origin;
    Vector3f dir;

    @nogc @system
    this(Vector3f *origin, Vector3f *dir) {
        this.origin = *origin;
        this.dir = *dir;
    }
}

How can I pass struct more efficiently?

Pass the Vector3f by value.

There is not one best solution here: it depends on what you are doing with the struct, and how large the struct is. It depends on whether the function will be inlined. It depends on the CPU. And probably 10 other things. Vector3f is a small struct (I'm guessing it's 3 floats?), pass it by value and it will be passed in registers. This "copy" costs nothing on x86, the CPU will have to load the floats from memory and store them in a register anyway, before it can write it to the target Vector3f, regardless of how you pass the Vector3f.

You can play with some code here: https://godbolt.org/g/w56jmA

Passing by pointer (ref is the same) has large downsides and is certainly not always fastest. For small structs and if copying is not semantically wrong, just pass by value. More important: measure what bottlenecks your program has and optimize there.

- Johan


Reply via email to