0
\$\begingroup\$

I discovered that Vector2's static methods return a different Vector2 from the parameters you give them and I'm under the impression that creating new objects and dereferencing old ones on this kind of scale (100's of method calls per update) is bad for the GC.

Is this the case with C# or does XNA pool these Vector2's for use on later method calls?

I ask because I want my entities collision shapes to share the same position Vector2 as the entity itself to eliminate the need to call updateBounds() after practically every position change. However since the methods return a different Vector2 the entities position and its respective bounds' position become differing objects.

Also is it worth making my own Vector2 class and have its methods non static so I can use someVector.add(otherVector) instead of XNA's way?

\$\endgroup\$
2
  • \$\begingroup\$ Premature optimization. Have you profiled this to see if it's actually a problem? It sounds like you're trying to fix a problem you're not even sure exists. \$\endgroup\$
    – House
    Jan 18, 2013 at 21:55
  • 1
    \$\begingroup\$ Thank you but I wasn't really asking for optimization purposes. It was more general curiosity about the how Vector2 is handled and also for the convenience of not having to update the AABB position vector whenever it's parent entity's position is changed. However I did not know it was a struct and that clears everything up. \$\endgroup\$
    – Mazk1985
    Jan 18, 2013 at 23:51

1 Answer 1

4
\$\begingroup\$

Vector2s in XNA are not objects, they are structs, which are not reference types. This is why you get a copy back from the methods. They will have entirely different allocation behavior than objects (stack rather than heap). If you manipulate them in certain ways, they can be "Boxed" into objects, which will use the heap. But if you use them properly, then they are no more of a memory waste than declaring int i in a for loop.

@Byte56 is exactly correct. You are optimizing for a problem that is not really a problem.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ +1 to any answer that says I'm correct. (And also insightful into the internal workings of C#). \$\endgroup\$
    – House
    Jan 18, 2013 at 22:18
  • \$\begingroup\$ ah I have read about structs and how they are allocated on the stack instead of the heap. This definitely clears things up and I would much rather stick with the pain of calling an updateBounds() method then lose the perfermence benefit of using structs. Thank you kindly \$\endgroup\$
    – Mazk1985
    Jan 18, 2013 at 22:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .