Structures, definitely. What for? Well, this is part of the feeling, I think the vector just feels and behaves like a value.
Rico Mariani here gives some reasons why value types were chosen for certain types for the API (I don't think he's XNA, he talks about).
Although efficiency is a factor here, I donβt think about garbage collection, but more about data density, for example, says Rico. Say you also have a Vertex type that contains two Vector3 s: a Vector3 for normal and a Vector3 for world coordinates. If you made these types of classes, then having an array with 100 Vertex elements will consist of:
- 100 * 8 bytes (8 bytes, I think, the overhead of a class in memory, 4 bytes for a type header and 4 bytes for something else, a GC handle?)
- 100 * 4 bytes (for pointers in an array for
Vertex elements) - 200 * 4 bytes (for pointers from each
Vertex to two Vector3 elements) - 200 * 8 bytes (for 8-bit premiums that you pay for creating a
Vector3 class) - 200 * 12 bytes (for actual payload 3
float per Vector3 )
6000 bytes (on a 32-bit system).
As a value type, it is just 200 * 12 bytes = 2400 bytes. Such a much more efficient space, not to mention a lower level of indirection when reading an array.
But taking up large space does not necessarily slow down, using the type of value incorrectly can be slower than making it a class, as I discovered . You definitely want to pass them ref as much as possible, do not copy them, but this is not suitable for all operations, so measure it. I think I remember that calculating a point product was slower when passing through ref , perhaps because it somehow prevented alignment by making IL larger. But don't take my word for it, just measure.
JulianR
source share