2

I have a struct called Vector2D. I use struct here to benefit from value types instead of references to instances, because vectors are intense with graphics generally. Last thing I want is thousands of vectors doing binary copies. Since the class just uses two floats (64 bits, then), it's not much of a concern, but I want to learn about this anyway.

I'd like to use operator overloading on my Vector2D struct. I'm worried this does at least three binary copies then: 1 binary copy with 'new', 2 binary copies passing in v1 and v2.

public static Vector2D operator +(Vector2D v1, Vector2D v2)
{
    return new Vector2D(v1.m_x + v2.m_x, v1.m_y + v2.m_y);
}

Is there a different way to make this more efficient for structs?

Bob
  • 115
  • 10
  • Being copied by value is the nature of structs, isn't it? I don't think you can improve this any further. And remember, premature optimisation is the root of all evil. – Sweeper Apr 01 '18 at 07:58
  • In C++ you can pass the reference of a structure with operator overloading. This seems to be not be the case with C#. I'm a little surprised, although 'in' helps with larger structs. – Bob Apr 01 '18 at 15:23

1 Answers1

0

In C# 7.2 you can avoid most of copying using in modifier.

public struct Vector2D
{
    double m_x;
    double m_y;

    public Vector2D(in double m_x, in double m_y)
    {
        this.m_x = m_x;
        this.m_y = m_y;
    }

    public static Vector2D operator +(in Vector2D v1, in Vector2D v2)
    {
        return new Vector2D(v1.m_x + v2.m_x, v1.m_y + v2.m_y);
    }
}

Make sure in your project settings you are using C# latest minor version and you are also running latest visual studio update. (goto project settings => build => advanced => choose language version)

in is like ref with a twist that is in parameters are readonly.

so you are passing v1 and v2 by reference without copying them. this is more helpful for larger structs. for small structs like yours I don't think it performs much better.

by the way I think there are better tools to manipulate vectors faster using GPU. I haven't done that my self but maybe look here and try it your self.

Utilizing the GPU with csharp

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 2
    Passing very small structs with `in` is actually slower than passing them by value. This is because 64/32bit value can be easily passed via register or pushed on to the stack. With references you have to copy reference by value and then load value of this reference. `in` was mostly designed for big structs where passing 64/32 bit reference is better than copying e.g. > 256 bit struct. – FCin Apr 01 '18 at 09:29