Ok, an easy question.
First of all, I have to say that my concern is not performance. I'm totally aware that whatever performance costs one option or the other may entail are probably meaningless and not even worth considering in normal scenarios. It has more to do with design standards and curiosity as to how the majority of coders would do it.
Ok, so the question is rather simple:
Suppose I have a ComplexNumber struct
which I could implement the following way:
public struct Complex : IEquatable<Complex>, IFormattable
{
readonly double realPart, imaginaryPart, magnitude, argument;
readonly static Complex j = new Complex(0, 1);
public Complex(double realPart, double imaginaryPart)
{
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
this.magnitude = Math.Sqrt(Math.Pow(realPart, 2) + Math.Pow(imaginaryPart, 2));
this.argument = Math.Atan2(imaginaryPart, realPart);
}
public double RealPart { get { return this.realPart; } }
public double ImaginaryPart { get { return this.imaginaryPart; } }
public double Magnitude { get { return this.magnitude; } }
public double Argument { get { return this.argument; } }
public static Complex J { get { return Complex.j; } }
...
}
The Magnitude
and Argument
properties have backing fields that are evaluated at construction time. Another option would be to simply evaluate the corresponding value in either getter.
What is the most recommended way to do this? Is there any coding standard that recommends any option for the sake of having a standard? And if there isn't one, what is normally the preferred choice? Or is it only performance dependant which in my case is irrelevant?
I would favor computing the values directly in getters, because it's more readable: If you want to know what Argument
does, just look at its code. If you cached the value in a field like you do now, you have to go Argument
property → argument
field → constructor.
If performance did matter, obviously the proper way to find out which option is better in your case is profiling. But as a guess, I think the version with values cached in fields will be slower too, especially if you don't use the computed values often. That's because struct
s are copied all the time and those fields make the struct
twice as big.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With