Does unused import and objects have a performance impact

JavaImportPackageBytecode

Java Problem Overview


I have a doubt, whether the unused imports and unused objects in Java code create any performance impact?

Suppose an object is initialized and never used, what happens? And what is the cost of unused imports?

Java Solutions


Solution 1 - Java

Its a very common question.

Like most performance questions the best approach is to write the clearest and simplest code you can as this improves the maintainability of the code and helps ensure it performs reasonably well even after it is changed. (Clever/Obtuse/Needlessly Verbose code can run fast to start with but as it is changed by mere mortals it can get much slower)

Unused imports have a trivial impact on the compiler, but there are no imports in the byte code or at runtime.

Unused objects can be optimised away, but its best to avoid these as they almost always cause some performance impact, but more importantly make reading and maintaining your code more difficult.

Solution 2 - Java

Unused imports have no performance impact at runtime. It is purely a namespace mechanism. Nonetheless, you should always import only what you need for readability and avoid namespace collisions which are a nuisance.

Apart from code readability and hence maintainability of code, there may be faster compilation of java code (however, unnoticeable) by tidying up imports, but runtime performance is not impacted, since byte code generated is not impacted by untidy imports. Byte code generated remains the same.

Solution 3 - Java

While impact in compilation is minimal, the impact in deployment can be bad. I've just come across an unused import that required a separate library which became a maven dependency. A further transitive dependency problem was fortunately not found, but the .war file was thicker for no reason. Add to that a superfluous jar in the webapp classloader.

Solution 4 - Java

Though unused imports in Java file do not create any harm, it unnecessarily increases the length and size of the Java source file.

Solution 5 - Java

Yes it impact a bit on performance, if we are referring unused import statement in our java class. The Java compiler will check for references mentioned into the import statement and at minute level it impact on the performance of the your class.

Thanks

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDheeraj JoshiView Question on Stackoverflow
Solution 1 - JavaPeter LawreyView Answer on Stackoverflow
Solution 2 - JavaFranklineView Answer on Stackoverflow
Solution 3 - JavaOssama BoughabaView Answer on Stackoverflow
Solution 4 - Javaasem shawkeyView Answer on Stackoverflow
Solution 5 - JavaNeerajView Answer on Stackoverflow