In the help for XNA Vector3, two of the public methods that it lists are Subtract and op_Subtraction. What’s the difference between them and when should one be used instead of the other?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
op_Subtraction(the-operator implementation) andVector3.Subtractare essentially the same thing. They create a new vector with values from a subtraction operation.Vector3is a value type, so there is no memory-management cost, however there is a small construction cost.The other overload of Subtract is slightly different:
This one takes references for its input and for its output. It is better for data-oriented programming (for example: a tight loop in, say, a physics engine, which takes data from one array and outputs it into another array). This removes the construction cost, and the cost of passing 6 floats as arguments, however there is still a tiny cost for the function call and dereferencing.
You can get even faster by doing the subtraction directly:
Of course, as you select faster options, you also lose readability! This is much clearer:
So to answer your question – you should absolutly use the vector
-operator when doing vector subtraction, unless you’re writing some kind of very high-performance data-oriented thing and you have profiled your code and found it to be a worthwhile performance improvement.If you’re interested in more low-level performance information like this, take a look at Understanding XNA Framework Performance by Shawn Hargreaves. (In fact it includes a benchmark comparing the three methods I have listed here, when used in a particle system.)