简体   繁体   中英

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. 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.

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.

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. There is a good SQLiteAssetHelper library to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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