I need to create a data transfer object, which I will use for storing the records retrieved from database. In this data transfer object, I need to declare a numeric field. For that which one is better - int or Integer
If I am defining the field as Integer, will there be any performance impact because of 'Integer' type if I am going to retrieve more than 2000 records from DB!?
Thanks in advance.
To give you an idea, 2000 Integer would add about 0.5 ms to you query. If you have to serialize this data it could add quite a bit more.
However, correctness should come first. There is no point being very fast but wrong. You have to consider null values and how you handle them. (Unless the column is NOT NULL) You could use Integer.MIN___VALUE or you could use a long field instead of int and use Long.MIN_VALUE for null. Even though it is larger than int, it would still be many times smaller and more efficient than Integer.
To my mind, the choice between declaring something as int or Integer simply comes down to whether null is a valid value for it or not. Autoboxing (and autounboxing) will take care of any conversion issues where the number simply must be one type or another. Performance (as has been pointed out) is also unlikely to be noticable in almost all cases.
Besides, int should be the natural choice, and is likely to be the most performant should that be an issue anyway. If you need to be able to store nulls, then you have to use Integer (and also ensure that no null references are auto-unboxed for a method that takes simply ints as this will result in a NullPointerException).
int is 10x faster than integer
we test this code with jetm performance library
and the results:
test:objects 10.184
test:primitives 1.151
You should really make your decision based on- what you need your object to do, rather than the performance costs. Deciding based on performance should be done, once a speed issue has been identified with a profiler - the root of all evil and all that.
Look at some of the features of both and use that for your decision, e.g.
Integer
can benull
,int
cannot. So is theint
in the DB aNullable
field?Integer
class methods?Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit.
int
can't be cast to theString
with using thetoString
or(String)
.Integer
can cast toString
withtoString
or(String)
and it can handlenull
.If you want to check for a
null
value thenInteger
is best but if you want to compare the integer then int may be better. In the following example I am using integer c= 1000 and d= 1000 and compare it return false but in case of int they will return true.