Structure Value Creation Performance

I am currently reading Oreilly Learning XNA 4.0 , and I noticed that the author is inclined to create a structure value like Vector2 or Rectangle several times without paying attention to performance.

For example, the SquareCollision() method, which checks for a collision between two game objects, creates two Rectangle each time it is called, instead of just having each game object in its own Rectangle field and comparing the fields without creating even more structure values.

I have seen this diagram many times in many places, and it made me think:
Is creating structure values ​​that are minor in C #?
Does this really apply to micro-optimization?

Perhaps because my experience is mainly related to Java, the concept of ValueType is strange to me, but it seems that re-creating a value from a struct (and the constructor calling it) several times seems like a huge waste of resources.

+6
source share
2 answers

Creating a structure for short use on the stack is very cheap and not much different from setting only local variables for all of these values, but using componentization. However, as part of the object, this will be an additional duplicate of the same data for each object.

Both approaches are valid depending on the scenario. However, there is no real cost of resources on the stack. As part of the facility, you want to make sure that you are not duplicating data unnecessarily, as this will have actual cost.

If this property is on an object, you will need to copy it many times.

If it were a field on an object, yes: it could be used in place without copying, but: in most cases, this is relatively small.

As always, you will need to know the profile, if that matters.

+6
source

The fact is that the presence of this structure inside your (say) Mesh object, in principle, will not do you any good. The reason at the time of the request to it, the value of the structure will be copied . Consider an 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 } } 

Therefore, using this way in your conditions, in principle, you do not get any benefit + you increase the size of the Mesh instance.

Instead of using / building this Vector3 instance inside the actual method, the moment you really need it, you quickly get stack allocation and quick garbage collection.

If you are not satisfied with performance in structures, you might consider using arrays of non safe data. But this is what you need to measure to see if this scenario is right for you.

+1
source

Source: https://habr.com/ru/post/908283/


All Articles