C # struct vs Class performace, design focus

How much performance gains can be achieved with struct over class? Should I design applications that maximize the use of structure over the class?

Can I convert my classes to a structure and move functions to other static classes where possible?

+5
source share
5 answers

The msdn recommendations (listed in another answer) offer some recommendations. For performance, you should consider their use and the distinction between structures and classes. The most important thing is to use only structures when the type is the actual type of value, i.e. It has semantics of meanings. Using a class for a value type or structure for something that needs to be a reference type will quickly lead to confusing results with manual copies or unintended references. Also remember that structures should always be immutable.

Only in extremely performance-sensitive situations should you ignore any of these basic rules (example: a structure violates the rules for a List.Enumerator structure!).

Perf considerations for structs vs classes:

If you pass your structure as an argument to a method, you will create a copy of the structure each time. This is why documents recommend that you do not create structures larger than 16 bytes.

double Distance(Vector3D a, Vector3D b) // Copies both 24-byte structs { return Math.Sqrt((aX - bX *....); } 

In the above scenario, a 3-doubling three-dimensional vector would be 24 bytes and would be larger than the recommended 16, but I would still argue that the structure makes sense, since this is clearly a value type, especially you have Vector2D containing two doubles (16 bytes) which are structure!

The key to making good use of structures and making them more efficient is to use them to localize the cache and avoid many distributions. To reuse the Vector example above if you have this method

 double AverageDistanceFromOrigin(Vector3D[] points) // Single reference passed { double sum = 0.0; for(...) sum += Math.Sqrt(points[i].X... + ... + ...) // No copies return sum/points.Length; } 

You can see a good performance difference in the structures. The reason is that now you pass one method (array) to the method, so there is no additional overhead for copying the structure for each call (note that the method does not call the distance method for each record in the array),

Array structures are also laid out sequentially in memory, for example [x1, y1, z1, x2, y2, ...], so the CPU will load, for example. 16 coordinates in the cache, which leads to several misses in the cache. Compare this with the implementation of class Vector3D : an array of vectors will now be allocated, and each entry in the array will also be a link, which should be allocated in a heap and then garbage collected. The array is now an array of links [ref to v1, ref to v2, ref to v3], each of which can have any address on the heap and cannot sit next to eachother. This can lead to even more cache flaws than to the case of structure.

  • Use structs only if your type has semantics of values ​​(and vice versa).
  • Do not pass large structures individually to methods; Work on lists / arrays of structures to avoid copying.
  • Don't consider the 16 byte limit a hard limit: you can use much larger structures, but remember to avoid passing them individually to methods.
+3
source

MSDN has good points for this:

✓ CONSIDER, defining a structure instead of a class, if the type instances are small and usually short-lived or are usually embedded in other objects.

X AVOID defining the structure if the type does not have all of the following characteristics:

  • It logically represents a single value similar to primitive types (int, double, etc.).
  • It has an instance size of up to 16 bytes.
  • It is unchanging.
  • It does not need to be inserted into the box often.

MSDN also has Struct Design.

Should I develop applications that maximize the use of structure over a class?

It depends on what you are trying to implement. Structures are used when you have small structures that you are trying to implement that will behave like values. Therefore, saying that using a struct over class is not an ideal statement or approach.

+8
source

Well, the short answer is: "You can, but you shouldn't."

The main difference between classes and structures is that the structure determines the type of value, and the class defines the reference type. Therefore, you cannot just replace the word "class" with the word "struct" and move functions, because the behavior of your program can be greatly affected by the above difference. Then, if you are developing a new application from scratch, you might think about whether you should define your logical objects using structures or classes, where appropriate, but then your code should keep that in mind. Hope this helps!

+2
source

How much performance gains can be achieved with struct over class?

For a “maybe,” the answer would be that you could be many times faster.

However, it can also be many times slower.

In most cases this will not be, but just give a small gain or loss.

Therefore, “I will use structures faster” is in itself wrong thinking.

If your starting point is to consider whether something should be a ValueType , because it really should be a value type; defined, used and reasoned - only in terms of its value or should there not be a ValueType , because it is not that type of value, then you will most likely have the most effective choice for this particular case 95% or more time.

Of the remaining 5%, probably 90% of them will be negligible if you go differently and / or they simply won’t be hot enough to make a difference. (Say you save 20 milliseconds for a given method. If this method is called a million times, then you saved five and a half hours of runtime, but if it is called as soon as you save 20 milliseconds, you won’t even notice).

In those cases where we really want to change values ​​and reference types for performance reasons, we could often switch from struct to class , and not vice versa. Indeed, it is so much so that the exclusion of value types larger than 16 bytes is a frequently cited guideline, although it is actually a performance optimization and not an integral part of what a value or reference type means.

It is also worth noting the differences in values ​​and reference types, invoking the code. There are several operations that can be much faster on arrays of mutable structures than on arrays (or any other collection) of mutable reference types. But taking advantage of these requires that you both make the fields public and value types change; which can cause significant difficulties. Such optimizations are reasonable for private types in the class that uses them, and when pressed for internal types, but if it is done with the public type, it asks for problems.

+1
source

Converting your structures to classes will not automatically improve the performance of your application.
It depends on how you use them, as well as how you used the class objects.

If you create and destroy many objects of a class, you can either reuse an object of this class, or create a structure and reuse it too
(so you see, you can do this with a class too).

When you call a method and send parameters or return a value,
the class is passed by reference , and the structure is passed by value .
Thus, here you can enjoy a performance boost if you miss it a lot.
(again, with good programming, you can even not pass all this time to the method, creating data as a field (classes) of the class containing methods).

Regarding your second question,
you can also have methods inside the structure, you do not have to move them to a static class.

 struct SimpleStruct { private int xval; public int X { get { return xval; } set { if (value < 100) xval = value; } } public void DisplayX() { Console.WriteLine("The stored value is: "+xval); } } 

https://msdn.microsoft.com/en-us/library/aa288471.aspx

0
source

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


All Articles