I have some amount of older game code that I am porting over to XNA. All of my objects use x/y (float) vs. Vector2 to describe various positions, etc.
Syntax, etc. aside, is there a good performance based reason to convert my old x/y type units to Vector2, or can I just do a straight port and not have to worry about it?
I'd say the main reason for using Vector2
is that it allows you to use overloaded operators, which makes code easier to read and understand.
In terms of performance, there would be so little in it, considering almost any game would be doing much more. If anything 2 floats might be faster, as accessing a variable might be faster than accessing a struct's field (although as Merlyn has said will probably end up the same anyway).
Using Vector2
is slower in two important ways:
Creating one can cause the constructor to be called (although in some typical cases it will be optimised out). This is an extra method call. (Note that it doesn't allocate memory.)
Calling methods - and that includes operators like +
and *
- involves a method call, which takes time. Doing maths operations directly on float
s (and that includes operating directly on the X
and Y
members of Vector2
- that is to say inlining the operators) doesn't involve a method call and is therefore faster.
To put an actual number on it - inlining simple operators (+
and *
) on Vector3
gives a 380% speed improvement (source: "Understanding XNA Framework Performance" by Shawn Hargreaves).
However it is a lot more convenient to use the vector classes as-is. So unless you are optimising maths-heavy code like a particle system or physics engine, don't worry about it!
(Also do note that the operators on the vector types, method calls included, are already insanely fast! Making an already-fast thing faster is not nearly as useful as making a slow thing faster! There are usually better performance improvements to persue.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With