Performance

Serialization is often the easiest way to save the state of your program. You simply write out the objects you're using and read them back in when you're ready to restore the document. There is a downside, however. First of all, serialization is slow. If you can define a custom file format for your application's documents, using that format is almost certainly much faster than object serialization.

Second, serialization can slow or prevent garbage collection. Every time an object is written onto an object output stream, the stream holds onto a reference to the object. Then, if the same object is written onto the same stream again, it can be replaced with a reference to its first occurrence in the stream. However, this means that your program holds onto live references to the objects it has written until the stream is reset or closedwhich means these objects won't be garbage-collected. The worst-case scenario is keeping a stream open as long as your program runs and writing every object created onto the stream. This prevents any objects from being garbage-collected.

The easy solution is to avoid keeping a running stream of the objects you create. Instead, save the entire state only when the entire state is available and then close the stream immediately.

If this isn't possible, you have the option to reset the stream by invoking its reset( ) method:

public void reset( ) throws IOException

reset( ) flushes the ObjectOutputStream object's internal cache of the objects it has already written so they can be garbage-collected. However, this also means that an object may be written onto the stream more than once, so use this method with caution.

Категории