c# - Does encapsulating a quantity in a struct for type safety have performance implications? -


i use convention (inspired f#'s units) catch classes of programming errors:

public struct inch : icomparable<inch> {     public readonly float value;     public inch(int value) : this() { value = value; }     public static implicit operator inch(float value) { return new inch(value); }     public int compareto(inch other) { return value.compareto(other.value); }     public override string tostring() { return value.tostring(); } } 

operations such addition performed thusly:

inch a, b; inch result = a.value + b.value; 

this allows inch passed low overhead of value type, advantage cannot accidentally assigned plain float. (i've found allowing implicit conversion in opposite direction i.e., of floats inches, not typically result in bugs.)

question: there known performance issues specifically example of addition shown. again question performance, have no questions semantics.

the biggest semantic problem here use of implicit operator, allows float value treated inch unit. should remove operator, or change explicit.

the biggest performance concern lack of overridden equals , gethashcode methods. should override both of these methods on default implementation provided valuetype may slower slower. runtime environments may detect class not directly or indirectly contain fields reference types , provide efficient implementation of these methods, no guarantee made regarding this.

for additional usability, define operator + performs addition, have following:

inch a, b; inch result = + b; 

naturally, same applies operator -.

theoretically, struct have performance overhead approaching zero, dependent on many aspects of runtime environment, especially ability inline methods. final answer whether or not overhead observable and/or acceptable can determined profiling use of type in expected environments expected inputs.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -