Basic Java Optimisation Hints

4. Collect your own garbage, with care

Java programs run nicely most of the time, but now and again they grind to a halt... that's garbage collection time !

Automatic memory management

A common performance complaint with Java programs is that they run nicely most of the time, but now and again they grind to a halt. As often as not the culprit is the garbage collector. Automatic memory management is a great feature, but it comes at a price. Collecting that garbage is a slow and difficult task and although most modern JVMs try to minimise the costs, when the collector-man comes knocking you will know about it. So what do you do?

Avoid garbage collection in first place by reusing your objects

Schedule the garbage collector yourself : System.gc()

Do this when things are quite

Well obviously the best thing is to avoid garbage collection in first place by reusing your objects (see tip #1). The alternative is to schedule the garbage collector yourself, at a time which suites you best. You can manually invoke the collector at any time by calling: System.gc(). The precise effect of this call will vary from JVM to JVM, but in general it will clean out the memory so that the collector won't need to run for a while. If you do this when things are quite it can save you some grief when things get busy.

Java3D : Usability studies : it is better to have a slow but constant frame rate than a fast but variable one

If you regularly schedule the garbage collector you can average out the costs

This technique is especially useful for Java3D applications. Most usability studies have concluded that for interactive applications it is better to have a slow but constant frame rate than a fast but variable one. Anyone who's played Quake will know there's nothing more annoying than a game where everything is ticking over nicely, then just as the action hots up the frame rate bombs out. Averaging 60 frames per second (fps) sounds great, but if that average varies from 20fps to 80fps it will be more annoying to users than if you simply maintain a constant 30fps. So if you regularly schedule the garbage collector you can average out the costs. Sure the highs won't be quite as high, but then the low's won't be quite as low either. (We'll see how this same observation affects behaviours in tip #12 and tip #15).