Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is class.getName() expensive?

Tags:

java

In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

like image 983
Tom Tresansky Avatar asked Aug 18 '11 14:08

Tom Tresansky


1 Answers

Here is the implementation of Class.getName()

public String getName() {
if (name == null)
    name = getName0();
return name;
}

As you can see the value of name is cached, so the call is not too expensive. It is just as call of regular getter. Anyway if you call it very often it is probably a good style to define constant.

like image 133
AlexR Avatar answered Oct 05 '22 10:10

AlexR