Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Using Generics in Java Affect Performance?

Tags:

Generics have been in Java since version 5. What are the performance implications of using generics in a Java application and can you explain the reasons for their performance impact?

like image 328
Kamahire Avatar asked Jun 03 '11 07:06

Kamahire


People also ask

Do generics make code more fast?

Explanation: Generics add stability to your code by making more of your bugs detectable at compile time. 2. Which of these type parameters is used for a generic class to return and accept any type of object?

Should I use generics Java?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

What is the point of using generics Java?

Java Generics helps the programmer to reuse the code for whatever type he/she wishes. For instance, a programmer writes a generic method for sorting an array of objects. Generics allow the programmer to use the same method for Integer arrays, Double arrays, and even String arrays.


2 Answers

Generics is a compile time feature. It has next to no impact when running your application.

Like most performance questions; it is far more important to write clear and simple code and this is often gives very good performance.

Changing your design for performance reasons is a so often a mistake some people say you should never do it. I think it is worth considering performance before you start but you have to recognise when you have a relatively trivial performance question.

You are better off writing your code and optimising it later when you have a better understanding of how you application behaves. i.e. when you are real use cases and a profiler.

like image 85
Peter Lawrey Avatar answered Nov 11 '22 05:11

Peter Lawrey


Is it affect the performance of an application and how?

No, it won't affect performance since it's not even there at runtime.

From the official trail:

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method.


As I've illustrated here both these programs translate to the very same bytecode:

import java.util.*;  class Test {     public static void main(String[] args) {         List<String> l = new ArrayList<String>();         l.add("hello");         System.out.println(l.get(0).length());     } } 

 

import java.util.*;  class Test2 {     public static void main(String[] args) {         List l = new ArrayList();         l.add("hello");         System.out.println(((String) l.get(0)).length());     } } 
like image 44
aioobe Avatar answered Nov 11 '22 05:11

aioobe