If you look at the source code of Sun's implementation of Class.getSimpleName()
, you'll notice it seems to return a new instance of String each and every time you call it. Many other features in the Class class is however cached.
Since the simple name computation does not seem to be easy and there's nothing in the JavaDoc to say it has to return a new instance every time, it should be a good candidate for caching. I am wondering could there be any design reason why this is not cached?
I am asking because many frameworks use simple names all the time and this is such an easy thing to cache.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With