Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the performance cost of primitive-acting structs?

Tags:

c#

I'm interesting in getting my numeric types more 'strong' in the sense that, for example, double values could be specialized to mean different things. Unfortunately, in C# the best I can come up with is writing something like using Real = System.Double; which really isn't useful because there is no static checking.

So I've been thinking about this idea of essentially wrapping numeric types in struct values, e.g.:

struct Real
{
  double Value;
  public static implicit operator double(Real r) { return r.Value; }
  // and so on
}

My question: what are the performance implications of this? Am I taking a significant hit compared to just biting the bullet and using double?

Edit: what I really want to have is a way of defining more stronly typed numeric variants so that a function Calculate(Rate rate) could not be called with an argument of type Percentage or even double, for that matter.

like image 214
Dmitri Nesteruk Avatar asked Feb 22 '23 08:02

Dmitri Nesteruk


1 Answers

In my experience, there is a performance hit to this, yes. You might expect the JIT to be able to effectively make it completely transparent, but I don't believe it does. (Of course different versions of the CLR may well behave differently in this respect, and future versions may improve further.)

Now as to whether this different is significant or not, you really need to test it - it'll be entirely application-specific. What are you doing with these values, and how important is it to the overall application performance? What is your required performance, and does your application already meet it? If you don't have any measurements in place, that should be your first port of call.

As a point of reference though, in Noda Time we have various structs which just wrap a long... but the API benefit from keeping those types distinct (and making them all distinct from just long) is massive. I care a lot about performance in Noda Time, but I certainly wouldn't change to use long everywhere just for the performance boost. It's all a matter of balancing the pros and cons - and we can't judge those for you.

(It's not clear to me whether your question stems from the same sort of wish to treat various values in different ways, even though they're just backed by double. I think that's what you mean, but it would be worth editing the question to make it clearer.)

like image 143
Jon Skeet Avatar answered Mar 02 '23 01:03

Jon Skeet