Performance Tip: Use static fields and classes.

Overview

Using a non-static field or a non-static class adds a field to each instance which may not be needed. It also improves clarity to show that a value does not change between instances or an outer class is not used implicitly.

Use a static field

From Writer.writeBufferSize
private final int writeBufferSize = 1024;
As this field is private and final it has to be the same for every instance. This makes it a constant, though its not clear this is the case.
private static final int WRITE_BUFFER_SIZE = 1024;
This makes it clear that every buffer will be the same size and saves a field from each instance (4-8 bytes).

Use a static class

The compiler will tell you if a class cannot be static. If you don't have code analysis tools, you can make an inner class static and if it compiles, it can be static.

From XMLEncoder.ValueData
private class ValueData {
    public int refs = 0;
    public boolean marked = false; // Marked -> refs > 0 unless ref was a target.
    public String name = null;
    public Expression exp = null;
}
You can see that Encoder.this is not required. Data Value objects rarely need to be non static as they don't have methods. However, many other classes don't need to hold a reference to the parent class.

Marking a class static makes it clear the outer class is not used implicitly and improves performance slightly.

Comments

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues