Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Class.getSimpleName() not cached?

Tags:

java

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.

like image 740
billc.cn Avatar asked Jun 28 '13 16:06

billc.cn


3 Answers

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.

like image 190
Basil Bourque Avatar answered Nov 10 '22 18:11

Basil Bourque


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.

like image 29
yshavit Avatar answered Nov 10 '22 19:11

yshavit


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.

like image 1
user2520968 Avatar answered Nov 10 '22 17:11

user2520968