开发者

Move a large instance method to shared, and create an instance stub -- good idea?

Quick question: If I have a very large function/sub in a class that is an instance method (i.e., not Shared), do I gain or lose anything by moving that to a shared method and then declaring a small stub method for the instance use?

I.e., I go from this:

Public Sub MyBigMethod(ByVal Foobar As String)
    If String.IsNullOrWhitespace(Foobar) Then
        Throw New ArgumentNullException("Foobar")
    End If

    ' Lots and lots of ugly code.
    ' Really.  There is lots of ugly code here.
    '
    ' Lorem ipsum dolor sit amet, consectetur adipiscing
    ' elit. Aliquam vel erat sit amet massa ultricies
    ' adipiscing. Mauris eu est ligula, a pharetra lorem.
End Sub

To This:

Private Shared Sub MyBigMethod(ByVal Obj as MyObj, ByVal Foobar As String)
    ' Lots and lots of ugly code.
    ' Really.  There is lots of ugly code here.
    '
    ' Lorem ipsum dolor sit amet, consectetur adipiscing
    ' el开发者_高级运维it. Aliquam vel erat sit amet massa ultricies
    ' adipiscing. Mauris eu est ligula, a pharetra lorem.
End Sub

Public Sub MyBigMethod(ByVal Foobar As String)
    If String.IsNullOrWhitespace(Foobar) Then
        Throw New ArgumentNullException("Foobar")
    End If

    Call MyClass.MyBigMethod(Me, Foobar)
End Sub

My thinking is I save on memory size per each instance of the object. Because each instance only has to lug around the stub method which handles calling the shared version and passing an instance of itself to the shared method so that it can do whatever it needs to do. But I'll wager that I sacrifice a very teensy amount of speed because of the added function call overhead.

Correct?


My thinking is I save on memory size per each instance of the object.

This is incorrect, because each instance does not store the method in memory. Instance methods are only stored in memory once. Function instructions are different than class members (which are stored per instance).

Furthermore, you gain a bit of a penalty by adding a function call, because the state of the stub method must be saved when calling the shared method. Then, it has to be loaded back when the shared method terminates. (Note: This is the same penalty you take when making any non-inline function call; the penalty becomes more stiff as the quantity and size of parameters increase)

You went down a logical line of thinking, but it was based upon the assumption that each instance gets its own logic instructions -- when they are actually used across all instances of a class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜