asteri
asteri

Reputation: 11592

Is there any performance or memory improvement between importing a class and using references with full class name?

I'm wondering if there is any difference between something like the following implementations:

import java.util.Date;

public class SimpleDatePrinter {

    public void printDate() {
        System.out.println(new Date());
    }

}

... and ...

public class SimpleDatePrinter {

    public void printDate() {
        System.out.println(new java.util.Date());
    }

}

The reason I ask is because my understanding from C++ include statements is that the contents of the included file are basically copied into the source file at compile time. I'm unsure if import statements in Java work in the same way, but if they do, would using the second construction shown above possibly save memory (since you are not importing the entire java.util.Date class into the SimpleDatePrinter? Or is this irrelevant?

I realize that writing code without ever importing a class would be detrimental to readability and whatnot. I also realize that in the example above it's "not enough to worry about." I'm just curious about this for cases in which performance is a crucial factor.

Upvotes: 1

Views: 159

Answers (2)

assylias
assylias

Reputation: 328775

Imports are resolved at compile time. In your example, the generated bytecode will be the same. And at runtime, the class (Date) will need to be loaded in any case. So it makes no difference from a performance perspective.

Upvotes: 5

sanbhat
sanbhat

Reputation: 17622

No, there is no difference. import statement is used to avoid using fully qualified names of the class we are using. The documentation doesn't talk anything about performance improvement

Upvotes: 5

Related Questions