6

Are there any technical reasons to "optimize imports" via your editor? Eclipse, Intellij IDEA, and NetBeans all have ways to optimize imports. I'm wondering if there are reasons other than consistency. Also, is there a more optimal way of importing? I've seen different standards that individuals and orginations have for optimizing imports. For example...

import java.util.Map;
import java.util.List;

import com.company.MyClassThatUsesMap;

If I understand right, in the above example the classloader will load the Map and List classes before MyClassThatUsesMap. Will this add any benefit to the speed at which the code will run versus the example below?

import com.company.MyClassThatUsesMap;

import java.util.List;
import java.util.Map;

Does this even matter at all or does the compiler fix it altogether?

Gordolio
  • 1,925
  • 15
  • 22
  • 2
    By the way: In Eclipse it is called _Organize Imports_ (not optimize). – Seelenvirtuose May 07 '15 at 14:08
  • 1
    Indeed and Netbeans too if I remember correctly, but Intellij confusingly calls it "optimize". A really poor choice of words since programmers tend to auto-associate "optimization" with speed. – Gimby May 07 '15 at 14:21

4 Answers4

14

If I understand right, in the above example the classloader will load the Map and List classes before MyClassThatUsesMap.

You don't understand right. Imports have nothing to do with execution-time handling. They only affect how the compiler resolves short names (e.g. Map) into fully-qualified class/method names.

The aim of "optimizing" imports is for readability - not execution-time performance.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I guess I was mistaken. Thanks for the info. For the sake of curiosity, do you know what determines the order at which classes are loaded? Is it the order in which they are used inside the class? Or is there no definite order? – Gordolio May 07 '15 at 17:14
  • 1
    @Gordolio: See http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.1 – Jon Skeet May 07 '15 at 17:50
2

There's no difference. It's only for the developer's eyes, although most IDEs hide the imports since the developer is rarely interested in seeing them.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

Rearranging import wouldn't effect the performance of your code. Java compiler is smart enough. Yes, you are right, that IDEs do it for consistency and code readability/maintainability. If you want to compare java.util.Map; with java.util.*; then it is different story all together.

Abhishek
  • 6,912
  • 14
  • 59
  • 85
1

Here is the official documentation. Optimizing the imports is not about speed. Its about cleaning up unused imports, and grouping similar packages together. It is mostly for readability.

It might change the order to put them in alphabetical order or another arbitrary order.

yxre
  • 3,576
  • 21
  • 20