简体   繁体   English

Java和Android中对象的范围和销毁

[英]Scope and destruction of objects in Java and Android

During the first launch (after the installation) of my Android application I create nearly 1000 objects and then save them in an SQLite database through greenDAO ORM. 在我的Android应用程序的首次启动(安装后)中,我创建了将近1000个对象,然后通过greenDAO ORM将它们保存在SQLite数据库中。 I'm new to Java programming and I'd like to ask if I can get better performance by putting in brackets in order to invoke object destruction through the garbage collector. 我是Java编程的新手,我想问一下是否可以通过放在方括号中以通过垃圾收集器调用对象销毁来获得更好的性能。

The code is: 代码是:

Foo foo1 = new Foo();
Foo foo2 = new Foo();
Foo foo3 = new Foo();
Foo foo4 = new Foo();
.
.
.
Foo foo1000 = new Foo();

And the idea for destroying objects in memory through scopes is: 通过作用域销毁内存中对象的想法是:

{
   Foo foo1 = new Foo();
   Foo foo2 = new Foo();
}
{
    Foo foo3 = new Foo();
    Foo foo4 = new Foo();
}
{
    .
    .
    .
    Foo foo1000 = new Foo();
}

So my idea is that the garbage collector frees objects from memory right after passing each bracket. 所以我的想法是,垃圾收集器在通过每个括号后立即将对象从内存中释放出来。 If this is not the right way, what is your suggestion to achieve better performance in this scenario? 如果这不是正确的方法,那么在这种情况下,您对提高性能有何建议?

In your case, if you don't ever need to simultaneously hold multiple instances of your class, you might as well create one object and re-use it 1000 times. 就您而言,如果您不需要同时保存类的多个实例,则最好创建一个对象并重复使用1000次。

Foo my_foo = new Foo();

for(int i = 0; i < 1000; i ++){
    my_foo.setValue(i);
    saveToDB(my_foo);
}

If those 1000 objects are always created the same you may want to distribute your application with a pre-populated database. 如果总是创建相同的1000个对象,则可能需要使用预先填充的数据库来分发应用程序。 There is a good SQLiteAssetHelper library to do that. 有一个很好的SQLiteAssetHelper库可以做到这一点。

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

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