简体   繁体   English

好的记忆课清理习惯?

[英]good memory class clean up practice?

I've recently been watching videos from google android devs about the importance of removing reference to objects when your done with them... I've implemented just a simple cleanup method. 最近,我一直在观看Google android开发人员的视频,内容涉及在完成对对象的引用时删除对对象的引用的重要性...我已经实现了一种简单的清除方法。 Will that actually work? 那真的行得通吗?

For example I do a lot of animation on views in my app. 例如,我在应用程序中的视图上做了很多动画处理。 to make things cleaner I do my animations for a activity in different class. 为了使事情更干净,我为不同班级的活动制作动画。 I pass a reference of the activity to the tweenanimation class. 我将活动的引用传递给tweenanimation类。

public void onStart() {
    tweens = new TweenUm(this);
}

and in my onStop I do... 然后在我的onStop中...

public void onStop() {
    tweens.cleanup();
    tweens = null;
    super.onStop();
}

my cleanup method looks something like... 我的清理方法看起来像...

public void cleanup() {
    mainAct = null;
    fab = null;
    fabcrad=null;
    searchFor = null;
}

mainact is the activity I passed in, plus other views i want to remove ref to. mainact是我传递的活动,以及我要删除参考的其他视图。

Will this do any good? 这会好吗?

It is not necessary to add a method cleanup . 不必添加方法cleanup

Because you are nulling the reference to the object tweens , if no other references are mantained in memory, tweens and all internal objects referenced only by tweens (mainAct, fab, fabcrad, searchFor) will be freed from memory by garbage collector. 因为你是置零的参考对象tweens ,如果没有其他参考文献都在存储器中,编程和维持tweens和仅通过补间引用的所有内部对象(mainAct,FAB,fabcrad,searchFor)将被从存储器通过垃圾收集器释放。

Use a cleanup method only to close resources (like files, sockets and so on). 仅使用cleanup方法来关闭资源(例如文件,套接字等)。

Note: while nulling tweens is important creating (and calling) cleanup is not a good choice, infact there are two possibilities: 注意:虽然使补间为零很重要,但是创建(并调用)清理不是一个好的选择,但实际上有两种可能:

  • no other references to tweens exists, so nulling internal references is not necessary 不存在其他任何关于补间的引用,因此不需要使内部引用无效
  • other references to tweens exists, in this case you probably will break internal state of tweens coming to a not valid state. 存在其他关于补间的引用,在这种情况下,您可能会破坏补间的内部状态,使其变为无效状态。

So generally if you don't need to close external opened resources it is not a good practice to use a cleanup method. 因此,通常,如果您不需要关闭外部打开的资源,那么使用清理方法不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM