Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting and Generics, Any performance difference?

I am coding in Android a lot lately, Though I am comfortable in JAVA, but missing some ideas about core concepts being used there.

I am interested to know whether any performance difference is there between these 2 codes.

First Method:

//Specified as member variable.   
ArrayList <String> myList  = new ArrayList <String>(); 

and using as String temp = myList.get(1);

2nd Method:

ArrayList myList  = new ArrayList(); //Specified as member variable.   

and using

String temp1 = myList.get(1).toString();   

I know its about casting. Does the first method has great advantage over the second, Most of the time in real coding I have to use second method because arraylist can take different data types, I end up specifying

ArrayList <Object> = new ArrayList <Object>(); 

or more generic way.

like image 331
sat Avatar asked Aug 02 '11 18:08

sat


2 Answers

In short, there's no performance difference worth worrying about, if it exists at all. Generic information isn't stored at runtime anyway, so there's not really anything else happening to slow things down - and as pointed out by other answers it may even be faster (though even if it hypothetically were slightly slower, I'd still advocate using generics.) It's probably good to get into the habit of not thinking about performance so much on this level. Readability and code quality are generally much more important than micro-optimisations!

In short, generics would be the preferred option since they guarantee type safety and make your code cleaner to read.

In terms of the fact you're storing completely different object types (i.e. not related from some inheritance hierarchy you're using) in an arraylist, that's almost definitely a flaw with your design! I can count the times I've done this on one hand, and it was always a temporary bodge.

like image 117
Michael Berry Avatar answered Oct 23 '22 12:10

Michael Berry


Generics aren't reified, which means they go away at runtime. Using generics is preferred for several reasons:

  • It makes your code clearer, as to which classes are interacting
  • It keeps it type safe: you can't accidentally add a List to a List
  • It's faster: casting requires the JVM to test type castability at runtime, in case it needs to throw a ClassCastException. With Generics, the compiler knows what types things must be, and so it doesn't need to check them.
like image 6
stefan Avatar answered Oct 23 '22 12:10

stefan