This is sort of a follow up question on Multiple Same Object Instantiation.
And I think, is not really language specific, so this is applicable to Java and C#?
Version A
public MyClass {
public void methodX() {}
public void methodY(int i, object o) {
GeometrySplitter splitter = new GeomterySplitter(int i, object o);
splitter.chop();
}
public void methodZ() {}
}
Version B
public MyClass {
private GeometrySplitter splitter = new GeometrySplitter();
public void methodX() {}
public void methodY(int i, object o) {
splitter.chop(int i, object o);
}
public void methodZ() {}
}
A colleague says that Version B is a better code practice, because the class is only instantiated once. My own reasoning is that the internal variable is only used in methodY(int i, object o)
and thus it should be created within the method itself, as displayed in Version A.
My colleague then reasons that if that method is called 4000 times a second. For every method call an new instance of that class is created. And this is bad for performance and memory use.
Is this true? If so or not, can someone clarify this?
Best Answer
Prefer version A unless you have a concrete reason to worry about the effect of many invocations of the method.
There is a general principle "variables should be declared as close as possible to where they are used", which should be followed unless you have a good reason not to. Version A obeys this principle, and has several benefits:
For this reason I would prefer A (without knowing anything else about how this code is used).
It's true that B is beneficial in specific cases. As your friend notes, if the method is invoked many times, version B would use memory more effectively (and it would also avoid repeatedly incurring the overhead of instatiating the object).
But worrying about this when you don't actually know you have a memory or performance problem is a classic case of premature optimisation. And there are actually cases where version A performs better. For example, what if your code involves creating thousands of
MyClass
objects, butMethodY
is rarely used? In this case, A may be the better design in terms of memory.