Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of creating struct values

Tags:

c#

struct

xna

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 Rectangles 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 ValueTypes 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.

like image 240
Acidic Avatar asked Feb 12 '12 22:02

Acidic


2 Answers

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.

like image 178
Marc Gravell Avatar answered Oct 24 '22 15:10

Marc Gravell


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.

like image 42
Tigran Avatar answered Oct 24 '22 16:10

Tigran