Say you are working with a simple class and object creation is not heavy:
class Simple {
public final int data1;
public final float data2;
...
}
You have to continuously put simple-objects into a queue:
queue.add(new Simple(123,123f,...));
Is it faster to work with an Object-Pool and change the Simple-Class modifiable class? I hope not.
Generally, no it isn't faster. If you configure the JVM to use a "throughput" GC, you will get better performance by not attempting to recycle objects. It is only worth considering object pools if either you are "memory constrained" or if GC pauses are problematic. (The amortized cost of garbage collecting an object tends towards zero as the proportion of garbage to non-garbage increases, especially if objects "die young", as per the generational hypothesis.)
In fact:
if the application is multi-threaded, the object pool may well be a concurrency bottleneck, and
mutation of the "effectively immutable" objects may well require additional overhead and/or additional synchronization.
If the object creation rate is "about 20 objects per second", then using an object pool is unlikely to make a significant difference to performance, even if it produces an improvement (which I doubt).
Do the math.
If the object size for
Simple
is N bytes, and you are allocating M per second, you can estimate the number of bytes per second allocated.If your "young space" is Y Mbytes, it will take T seconds to trigger a GC based on that allocation rate.
If the "young space" GC takes on average G ms for a space of size Y, you can estimate an upper bound on the time that could hypothetically be saved ... assuming that the object pool had zero associated overheads.
The actual saving will be less, because the "zero overheads" assumption is unrealistic.
In fact the time take to do a "young space" collection doesn't just depend on its size. It also depends on amount of non-garbage that needs to be retained. (Less non-garbage retained is better!) That can make the GC overhead hard to estimate. However, if you have already coded your application without an object pool, you can measure the average "young space" collection time for your application with a typical workload, and then plug that into the calculations above.