I think the answer depends on what, exactly, you're actually trying to do here. Conceptually, the fundamental question is, do you the programmer think of the state of anExistVar
after either updating its members or reassigning it entirely as a fundamentally new entity in your program? Or is it merely a modified version of the old thing?
If it's simply a modified version, why are you updating all of the member variables at once? The old object and the new one share the same name and memory location, but logically they don't seem to have any relationship between them. Note, however, that if you intend to update all member variables but fail to do so, you may think that there is no relationship between the old state and the new state and thus fail to realize that there is some holdover from the old state. In particular, there may be private member variables that have no corresponding public set
methods, so you may not be able to entirely transform the object even if that's your intention. In short, this kind of radical transformation of an object is confusing because it's not immediately clear what you're doing or why, or whether you'll actually be successful. If, however, you think that the modified object is still essentially the same object (with, for instance, some of the original data), then it makes far more sense to modify the existing object than to make a partially-faithful copy.
If you're creating something fundamentally new, then it's probably best to declare it as a new
object. If you want there to be some sort of relationship between the old object and the new object, there are a variety of techniques you could use, such as a static
class member to keep track of the total number of instances of that class that have been instantiated. Or, if you want the construction of your new instance to be partially determined by public attributes of the old instance, then explicitly pass those attributes to the constructor.
As far as efficiency and the garbage collector go, there's probably no reason to be concerned either way. The point of the garbage collector is to relieve you the programmer of the burden of explicitly deleting things; you can't explicitly control its behavior, and it behaves efficiently enough that you really shouldn't have to worry about it. Running out of memory is more of a concern than overburdening the garbage collector. In the particular case you're describing, yes, the garbage collector will need to delete the old object, but that won't have a significant impact on the collector's efficiency. It would be problematic to maintain references to objects you no longer need, because the garbage collector wouldn't be able to collect those objects in case you reference them later; since that's not what you're doing here, it's probably best to just do whatever is clearest from a programming and logical standpoint.