I'm currently reading Oreilly's Learning XNA 4.0 and I've noticed that the author is prone to creating a struct value, such as Vector2
or Rectangle
multiple times with no regard for performance.
For example, a SquareCollision()
method, that checks the collision between two game entities creates two Rectangle
s every time it is called, instead of simply having each game entity hold its own Rectangle
field and compare the fields without creating any more struct values.
I've seen this pattern many times in many places and that made me wonder:
Is the creation of struct values that negligible in C#?
Does this really fall under the micro-optimizations section?
Perhaps because my experience is mostly with Java, the concept of ValueType
s is strange to me, but it seems that recreating a value from a struct (and calling it's constructor) multiple times seems like a giant waste of resources.
Creating a struct for brief use on the stack is very cheap, and is not much different to just setting local variables for all those values, but with componentisation. However, as part of the object it would be an additional duplicate of the same data per object.
Both approaches are valid, depending on the scenario. On the stack, however, there is no real resource cost. As part of an object, you'd want to make sure you weren't duplicating data unnecessarily, as that would have actual cost.
If it were a property on an object, you'd need to copy it lots of times.
If it were a field on an object, yes: it could be used in-place without ever copying, but: this is relatively small in most cases.
As always, you'd need to profile to know if it mattered.
The thing that having that struct inside your (say) Mesh
object will not benefit to you, basically. Cause at the moment of the request to it, the value of the struct will be copied. Consider example:
public class Mesh
{
public Vector3 MeshCogVector {get;set};
}
and somewhere in the code you have
public void CollisionDetection
{
for(int i=0;....)
{
Mesh curmesh = listofmashes[i];
Vector3 vec3 = curmesh.MeshCogVector; //value copied
}
}
So using in this way in your conditions, you basically don't get any benefit + you increase your Mesh
instance size.
Instead using/constructing that Vector3
instance inside actual method, in the moment you actually need it, you get fast on stack allocation and fast garbage collection.
If you don't satisfied with a performance in structures, can consider of using non safe
arrays of data. But this is something that you should to measure, in order to understand if this is suitable scenario for you.
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