Jose M Lechon
Jose M Lechon

Reputation: 5896

Android efficiency importing static methods or importing the class

I've seen in some projects people importing directly a static method into an Activity or a class instead of the whole class.

My question is, knowing that a static method can be called several times (for being more accurate, 5 or more times) in the same class, is it more efficient to import the static method or it is better to call it through its class?

Upvotes: 5

Views: 903

Answers (2)

Droidekas
Droidekas

Reputation: 3504

Your question (according to me) does seems to address the same point. The question is if: is calling ClassName.staticMethod() directly

or this

import static ClassName.staticMethod;
//rest of the stuff
staticMethod();

In both cases, the methods are loaded as a singleton whenever the class is called first.If you import the static method,then thats the first time or else when you use the class's method.

So it wont make a difference because the JVM/DVM (not sure about ART) already has the data required.

IF however your question is regarding what modifiers to use,then this advocates static.

But as mentioned,involving static methods directly is just messy. So now its more of a personal choice. Read as:Do not import static methods directly unless you have a very specific reason to do so.

Upvotes: 4

David SN
David SN

Reputation: 3519

There is no difference in performance between static imports and import the class.

However, import the class and use the class name to call static methods is considered a better practice, because the code is more easy to read. With static imports it could be a bit confusing which methods are non-static methods of the class and which methods are static methods of other classes.

Upvotes: 2

Related Questions