Why is Class.getSimpleName() not cached?

Interesting question. Since String is an immutable class, it doesn't really matter if you return distinct instances or a reference to the same object. My guess would be (and I'm giving it mostly to hear if I'm right or wrong) that maybe the method is not called very often and it makes more sense to re-create the (String) object than to store it in memory. But again, this is just a guess.


Update: Name cached in OpenJDK 11

The class name is cached, in OpenJDK 11 and later. See the OpenJDK source code for Class.java and search for private ReflectionData<T> reflectionData() method called from the getSimpleName method.

For details, see ticket JDK-8187123.


Probably because it's not an expensive method, so there's not much to gain in caching it.

String.substring is a cheap method -- it reuses the underlying char[] without copying it, and the new String object just has a different offset and length into that array. So really the only costs are (1) the object allocation -- which is pretty cheap in Java -- and (2) the lastIndexOf call. That call is technically O(N), but N here is the class's simple name, which is not going to be very large in practice.

You could cache it, but at the cost of more memory. My guess would be that someone made the subjective but educated guess that the benefits don't outweigh the costs.

Tags:

Java