Caching is often not a good idea in Java . Creating new objects is usually much cheaper than you think, and often leads to better performance than storing objects cached "just in case". Having a large number of long-lived objects is bad for GC performance, and can also put significant pressure on processor caches.
JPanels, for example, are light enough that it's great to create a whole new one when you need it.
If I were you, I would cache as little as possible, and only so when you have proven the substantial benefits of this.
Even if you need to cache, consider using a cache that uses Soft References - this way the JVM can clear items from the cache automatically if memory needs to be freed. This is easier and safer than trying to flip your own caching strategy. You can use an existing Soft Reference cache implementation such as Guava CacheBuilder (thanks AlistairIsrael!).
source share