开发者

VB - What are the performance consequences of this questionable practice?

开发者 https://www.devze.com 2023-04-01 10:01 出处:网络
I come from a C# background so I\'m not quite up to snuff on my VB just yet. I\'ve run across this practice all over our code base and it is never used for chaining.

I come from a C# background so I'm not quite up to snuff on my VB just yet.

I've run across this practice all over our code base and it is never used for chaining.

I am wondering what performance consequences (if any) this might create.

Public Function Save(ByRef myObj As MyBusinessObject) As MyBusinessObject
    'Do save stuff
    'Return object we just saved
    Return myObj
End Function

'usage
myO开发者_运维问答bject = Save(myObject)


I am wondering what performance consequences (if any) this might create.

You're adding an extra assignment to the variable, but it's not really going to cause a performance issue. It's effectively just doing this C#:

public MyBusinessObject Save(MyBusinessObject myObj)
{
     // Do save stuff
     return myObj;
}

And then calling:

myObj = Save(myObj);

This re-sets the variable reference, but points it to the same object in memory, so there's little consequence. It's fairly standard practice for instance methods, though, as it allows for chaining (which you mentioned), ie:

myObj.Load(...).DoSomething().Save()

As you're not chaining, I suspect this was done by somebody who doesn't properly understand how object references work when calling methods.


This sort of construct allows for the possibility that the method might return a different object from the one it started with. I don't know that this would be useful for a "Save" method, but it can sometimes be useful with objects that may or may not be mutable, as a means of achieving "copy on write" semantics. For example, suppose the class was a some type of collection. If the proper method of doing an "add" were to say "myThing = myThing.Add(newItem)", and it was explicitly unspecified whether the call will mutate and return the original object, or whether it will create a new object which contains those items in the original along with a new one, then it would be possible for some class instances to be marked as shared-immutable (in which case one could have many semantically-different references to the same instance), while others were marked as unshared-mutable (in which case one could mutate the item without having to copy it).

0

精彩评论

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

关注公众号