C# operator overloading performance -
i looking @ c# basic example of operator overloading:
public static vector operator + (vector lhs, vector rhs) { vector result = new vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; } and wondering, performance-wise same thing overload + operator this?
public static vector operator + (vector lhs, vector rhs) { vector result = new vector(); result.x = rhs.x + lhs.x; result.y = rhs.y + lhs.y; result.z = rhs.z + lhs.z; return result; } are there differences first , second example? what's best solution , why?
your second method written incorrectly: you're adding .x property of rhs everything. i'm going assume simple mistake, , meant have same behavior between 2 methods.
these 2 examples call different constructor overloads, haven't included code for. if can assume first example's constructor sets x, y, , z properties on object, difference should first 1 needs load value .x, .y, , .z properties before can set them, have slower performance.
however, performance difference negligible, unless performance-critical piece of code, better focus on readability.
personally, i'd this:
public vector(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public static vector operator + (vector lhs, vector rhs) { return new vector( rhs.x + lhs.x, rhs.y + lhs.y, rhs.z + lhs.z; ); }
Comments
Post a Comment