Tutorial :Changing values in place instead of creating new instances



Question:

Basically I have checked out xna and some of slimdx (Promit :)), which has lots of structs. Pretty much all methods that looked like this:

public static Vector3 operator + ( Vector3 a, Vector3 b )  

where doing stuff like:

Vector3 c = new Vector3 ( ... )  

I am wondering if it makes sense to just do:

a.X += b.X  ...    return a  

Obviously #1 looks more sensible/reasonable, but #2 doesn't create a new Vector3 which is faster.

I think it's fast and as clear, if not more clear as #1.

Which one is better? Is there any problems with #2?


Solution:1

The only problem with 2 is that, since Vector3 is a value type (for good reason, see Rico Mariani's blog for details), you can't edit in place when they're part of collections or being used as a property member.

For example, it's very common to have a List<Vector3> member, but if you do:

myList[150].X += ...;  

It fails, since the indexer returns a NEW struct (value type semantics). It's usually safer with value types to treat them as immutable, which requires your first syntax.


Solution:2

I really doubt that you're going to have to worry so much about performance that you need to do this. Do the #1.

"Premature optimization is the root of all evil." - Donald Knuth


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »