Constructors calling other constructors: any performance issues?
In an application where performance is crucial, would there be any noticeable advantage of Scenario 1 (completely separate constructors) vs. Scenario 2 (chain-calling constructors)?
Scenario 1
Class TwoInts
Private a, b As Integer
Public Sub New(ByVal a As Integer, ByVal b As Integer)
Me.a = a
Me.b = b
End Sub
Public Sub New(ByVal a As Integer)
Me.a = a
Me.b = 0
End Sub
Public Sub New()
Me.a = 0
Me.b = 0
End Sub
End Class
Scenario 2
Class TwoInts
Private a, b As Integer
Public Sub New(ByVal a As Integer, ByVal b As Integer)
Me.a = a
Me.b = b
End Sub
Public Sub New(ByVal a As Inte开发者_如何学Goger)
Me.New(a, 0)
End Sub
Public Sub New()
Me.New(0)
End Sub
End Class
No, there wouldn't be a noticeable difference.
You can run your own benchmark and find out.
The speed should not be very different. Thjere are only 2 more calls from the bare constructor to the deep one... but:
You should ask the language C# what it thinks about constructors that call constructors :P There it would not go very well, so I think you should stick with a different approach like making an "Initialization method", and call that from each constructor, and have a more readable code. There you would need to use the ": this(0)" Notation which is not so readable (eg. procedural when reading it). And it would have one less call to get to the point of doing something.
It depends on what you mean by noticeable. Scenario 1 does introduce extra calls, but the time it adds will be measured in fractions of a millisecond. Scenario 2 will be faster. (It will also increase the size of the generated code.)
Don't use a common Init() method as proposed by Marino Šimić! It is C++ style and not suitable for C#. In C# initialization should be done in the constructors!
For details see Bill Wagners book "Effective C#":
http://www.diranieh.com/NETCSharp/EffectiveCS.htm#14._Use_Constructor_Chaining
精彩评论