cyprieng
cyprieng

Reputation: 746

How to optimize memory without calling System.gc();

I am currently making an application that scan a folder and create Song for each file.

[loop]
         if(!alreadyInLibrary(folder.getAbsolutePath())){
            Song s = new Song(folder.getAbsolutePath());
            this.addSong(s); // Add the song

            // Clear
            s = null;
            System.gc();
          }
[end loop]

If I call the GC my app consumme 150Mb of memory and 400Mb without. But calling GC each time is really slow. So, I wonder if there is another way to optimize memory.

Thanks

Upvotes: 0

Views: 216

Answers (2)

Cruncher
Cruncher

Reputation: 7812

Song s = new Song(folder.getAbsolutePath());
this.addSong(new Song(folder.getAbsolutePath())); // Add the song

// Clear
s = null;
System.gc();

This is asinine. The most memory efficient way to do this is simply:

this.addSong(new Song(folder.getAbsolutePath())); // Add the song

You never used s. You just created it, then set it to null, then GC'd it. Instead just add it directly. No need to do any premature optimization of this.

There's no need to call the GC. It will run when it needs to. You generally never really need to call GC.

Upvotes: 0

AlexR
AlexR

Reputation: 115328

Generally you should never call System.gc(). GC is a sophisticated software component and it knows itself when to work and how much memory to free on each cycle.

Moreover explicit invocation of System.gc() does not really call GC. It just politely asks GC to work. It can start, but can postpone the request.

This means that if you do not call GC the program runs until GC determines that it should work and then frees it. So, the answer to your question is "just do not worry about the memory. Let GC to do its work when it thinks it is the time to work."

But. All this is relevant only if you do not have memory leaks that can happen for example if you store some not needed information in long-live collections. Such entries should be cleaned programmatically.

The "right" way to work with GC in java is via various -X command line switches. The first step is just try to reduce the max heap limit, e.g. -Xmx180m. Why 180? Just because you said that when you invoke GC it occupies 150M. Now try again. If program runs well and performance is better now, try to reduce memory even more. Take a look on other GC configuration parameters if it is needed.

Upvotes: 1

Related Questions