java - Consistent use of primitives and wrapped primitives -


if use int specific variable, have deal kind of collection it, means int converted wrapped int/int object , vice versa many times, makes sense in case, performance-wise , semantically better use integer variable, avoid constant casting between int , integer (i.e. when add int collection, have casted integer (actually have newly created), , when collection, have casted int)?

to consistent, there 2 possibilities here:

but if don't have special case here , tracked performance issues down casting, performance impact of casting negligible here. should not worry such micro optimizations if don't need to.


using wrapper classes not bring benefit, too. think following code:

list<integer> numbers, squares;     //initialize both, fill numbers      for(integer number: numbers)         squares.add(number*number);      for(int i: numbers) {         squares.add(i*i);     } 

in first loop, number straigt collection without casting, casted int, multiplied itself, , autoboxed integer before storing in squares.

in second loop, convert integer int when fetching list, multiply itself, , autobox integer before storing it.

in both cases, have autoboxing involved. avoid this, had use primitive collections, or int[].


Comments