Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
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. –  Byte56 Jan 18 '13 at 21:55
1  
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. –  Mazk1985 Jan 18 '13 at 23:51
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
1  
+1 to any answer that says I'm correct. (And also insightful into the internal workings of C#). –  Byte56 Jan 18 '13 at 22:18
    
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 –  Mazk1985 Jan 18 '13 at 22:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.