Good practise to avoid memory leak
I'm computing for android. I try to be carefull about memory leaks because my program is dealing with lots of data, and the garbage collector seems to be very busy.
I was wondering is there a difference beetween :
for (int i=0;i<200;i++)
{
MyObject myobject = new MyObject(i,i+1);
myobject.writeToDatabase();
}
and
MyObject myobject=null;
for (int i=0;i<200;i++)
{
myobject = new MyObject(i,i+1);
myobject.writeToDatabase();
}
and (avoiding to use the constructor)
MyObject myobject=new MyObject(0,1);
myobject.writeToDatabase();
for (int i=1;i<200;i++)
{
myobject.setFirstValue(i);
myobject.setSecondValue(i+1);
myobject.writeToDatabase();
}
Thanks !!
The third option is by far the best. The two other options are pretty much identical in Java, in that context.
If you do not create a new object every time, and instead use the old one again, you are relieving your garbage collector of a lot of work. This is a good way to make your performance and memory management a lot more efficient.
In the two first options, you are basically doing the same thing: making a new object at the beginning of the loop, and letting it get destroyed at the end of the loop. The fact that you keep using the same variable for the pointer doesn't make much of a difference.
Edit:
As said by Stochastically, your code would not cause any memory leaks though, simply for the fact that the garbage collector will make sure that doesn't happen. I'm guessing that there are some tricks to cause memory leaks after all, but in normal situations that just won't happen. But as I explained, you still have ways to make your garbage collection more efficient by using fewer objects.
链接地址: http://www.djcxy.com/p/19832.html上一篇: VisualVM无法在Eclipse上分析Web应用程序
下一篇: 良好的做法,以避免内存泄漏