Is a structure wrapping a primitive value type a zero cost of abstraction in C #?

Sometimes I want to add more types of security around raw doubles. One idea that appears a lot would be to add information about unit types. For instance,

struct AngleRadians {
  public readonly double Value;
  /* Constructor, casting operator to AngleDegrees, etc omitted for brevity... */
}

In a case like the one above, where there is only one field, can the JIT optimize this abstraction in all cases? What situations, if any, will lead to additional generated machine instructions compared to similar code using a deployed double?

Any mention of premature optimization will be reduced. I am interested to know the truth.

Edit: To narrow down the questions, here are a few scenarios of particular interest ...

// 1. Is the value-copy constructor zero cost?
// Is...
var angleRadians = new AngleRadians(myDouble);
// The same as...
var myDouble2 = myDouble;

// 2. Is field access zero cost?
// Is...
var myDouble2 = angleRadians.Value;
// The same as...
var myDouble2 = myDouble;

// 3. Is function passing zero cost?
// Is calling...
static void DoNaught(AngleRadians angle){}
// The same as...
static void DoNaught(double angle){}
// (disregarding inlining reducing this to a noop

, . , , @EricLippert, , . , , , , , JIT , , ,

+4
1

, DoNaught . , .

0

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


All Articles