Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: Vector2 vs. x/y

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?

like image 584
A.R. Avatar asked Jan 19 '23 08:01

A.R.


2 Answers

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).

like image 110
George Duckett Avatar answered Feb 05 '23 00:02

George Duckett


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 floats (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.)

like image 20
Andrew Russell Avatar answered Feb 04 '23 22:02

Andrew Russell