C#: is it better to store a reference or to pass it as a parameter?
I have a parent object that m开发者_StackOverflow中文版aintains a list of child objects. Periodically, it iterates through the list of child objects and calls a DoWork method on each one. Occasionally, the child objects have to refer to the parent object in the DoWork method. Is it better to store a reference that points back to the parent, using up 4 bytes (right?) times the number of children of memory, or to pass a reference to to the parent as a parameter every time the DoWork() method is called? What is the overhead if any of passing an extra parameter? Does MS .NET differ from Mono in this respect?
when a subroutine is called a stack frame is set up to hold all the input parameters and local variables defined either in the called methods' signature, or as local method-scoped instance fields. So whether you pass it in as an input parameter or store it as a local field, should not make much difference.
More important, is whether or not the method in question can ever be called from code other than in the parent object, where the parent might not be available... If so, then you need to store the reference as a private field of the child.
Either is about the same overhead i.e. minimal.
However if the children can ever be detached from the parent or reattached to another parent then you have the overhead of managing the stored reference in the child.
Personally I think pass the 'this' from parent each time is the best way.
Trivially, it seems a better idea to pass a reference to the parent to the method rather than storing it. The best reasoning that I can come up with is that a method argument will put less pressure on the garbage collector than a stored reference would be. The reference is not subject to garbage collection because it is automatically cleared when the call stack exits. Plus, if you ever need to pass a different instance, you can do so easily.
精彩评论