for example
Aclass myAclass = new Aclass();
for(int i=0;i<n;i++)
{
myAclass.load(i);
myAclass.do();
myAclass.clear() // clear the state of myAclass, rdy for next iteration.
}
or what if I embed the `myAclass.load() into the class constructor, and do sth like:
for(int i=0;i<n;i++)
{
Aclass myAclass = new Aclass(i);
myAclass.do();
}
So which way is better practice?
btw, the title seems not fitting the content, help me with a more appropriate title.
Note: Constructor of Aclass is trivial, Load() is not, Clear() is trivial
(of course the constructor in the 2nd example is not trivial as it triggers Load().)
There is no way to tell which approach is best in terms of performance, it depends on the implementation of the class.
Now, as a general rule, you should avoid mutable objects, so reusing the same instance of the class to do something else is usually not a good idea. So I would favor the second approach. Of course, if the initialization of the class is an expensive operation, the first approach will be faster…
As for memory usage, the second approach will create more instances in memory, but they will eventually be collected by the GC, so it shouldn’t be an issue. The only drawback is that it puts more pressure on the GC, so it could negatively affect performance if there are many iterations.