Which one to use, int or Integer
Asked Answered
L

11

78

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.

Lesson answered 8/1, 2009 at 9:38 Comment(2)
You will most likely find that the overhead of physically getting data moved from the database to your program overwhelms the performance impact of an Integer-wrapper.Ebon
I guess this would also help: softwareengineering.stackexchange.com/questions/203970/…Alkyl
T
150

Integer is a better option, as it can handle null; for int, null would become 0, silently, if resultSet.getInt(..) is used. Otherwise, it might throw some exception, something like, "Unable to set null to a primitive property".

Performance is of little concern here.

  • if you choose int, you will end-up adding extra handling code; and that wouldn't benefit you much. Your code will not be clean and straight-forward, lot of boiler-plate code, and you wouldn't even gain performance.
  • let me make it clear, for databases, null is not same as zero. Sometimes you end-up entering 0, where null was intended. Imagine the case where user submitted a form, and doesn't supply any value for int. You will end up getting 0 by default. It makes sense, or does that really, when that field is not null in the database.
Tinkle answered 8/1, 2009 at 9:44 Comment(7)
Adeel, I think you should edit your answer to include the information in your comments. They are relevant to this discussion and might be missed by some people just glancing at the answer.Karlsruhe
@Adeel: How would null silently become 0?Norite
@ William Brendel. I included my comments into original post. Thanks.Tinkle
@ Hemal: java.sun.com/javase/6/docs/api/java/sql/…Tinkle
For more info on the null<->int problem and other ORM issues, take a look at [Impedance Mismatch][1] [1]: en.wikipedia.org/wiki/Object-Relational_impedance_mismatchInsphere
getInt(int) returns an int - null will already have been silently converted to 0. Instead you should use isNull() in your DAO to check nullable columns, and then you can either use a null Integer, or a magic number (-1) in your model, depending on your needs.Pliam
Performance might be of concern once you start using this code. If your code includes a lot of "int blah = object.getBlah(); doCalcsOn(blah); object.setBlah(blah)", then this code will incur at least one new object creation every time it's executed. Something to keep in mind.Chartography
I
28

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 be null, int cannot. So is the int in the DB a Nullable field?
  • Do you need access to the Integer class methods?
  • Are you doing arithmetic?

Personally, I always opt for the primitive over the wrapper. But that's just a preference thing, rather than based on any technical merit.

Insphere answered 8/1, 2009 at 9:54 Comment(2)
auto-boxing would take care of it, if it happens to be once. Otherwise, cast it before performing any heavy calculation.Tinkle
True, but if you're doing multiple calculations dotted around you might want to go with the int option to avoid the multiple castsInsphere
M
12

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).

Marquismarquisate answered 8/1, 2009 at 10:54 Comment(0)
L
5

Integer is theoretically slower than int, however the performance impact should be minimal unless you are crunching numbers. Also JIT optimizations will reduce the performance loss.

Use the one that better suits your situation in terms of primitive or reference type.

Langevin answered 8/1, 2009 at 9:43 Comment(0)
T
4

int is 10x faster than integer

we test this code with jetm performance library

int n;
EtmPoint point1 = etmMonitor.createPoint("test:objects");
for (n = 0; n < 1000000; n++) {
    Integer t = 0;
    t = 10;
    t = 11;
}

point1.collect();
EtmPoint point = etmMonitor.createPoint("test:primitives");
for (n = 0; n < 1000000; n++) {
    int t = 0;
    t = 10;
    t = 11;
}
point.collect();

etmMonitor.render(new SimpleTextRenderer());

and the results:
test:objects 10.184
test:primitives 1.151

Towelling answered 4/11, 2010 at 6:30 Comment(3)
int is many times faster, however even in your example, you did one million iterations to see the difference. Try just 2000 values as the OP will be using. Also you should test the option you believe to be the fastest first to avoid any basis created by a JVM which has not warmed up.Mauer
2000 items or making the test from Integer to int will make the same result. int is faster then Integer. Keep in mind that Integer is a class and the code above could be translated as C++ to something like this: for(n = 0; n < 2000; n++) { Integer *t = new Integer( 0 ); t->privateJVMSetValue( 10 ); t->privateJVMSetValue( 11 ); } Of course null is possible with an object. And if you need it, indeed, int is not what you want to use.Gallows
This benchmark is way to small and primitive to show anything at all. Not the it means anything, but the following are the times I get after adding a warmup round: Integer Loop: 0.0018 s, Int Loop: 0.0020 s. Probably most of what happens in the loops gets optimized away.Hal
M
2

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.

Mauer answered 30/3, 2009 at 6:4 Comment(0)
S
2

int is used by java for most all calculations. Integer is used in all forms of Collections except for primitive arrays.

Using lots of temporary Integers with thrash the garbage collector and use unprofilable CPU in the background that will cause general slowdowns in everything. Too many temporaries being trashed per second will cause the CG to enter emergency "I need memory now" mode that can cause stalls in latency critical applications (ie: real time interactive graphics, physical device controllers or communications)

So for me if I have a lot of nested calls that do no math but access a lot of collections such as using keys for maps I use Integer so as to avoid tons of auto boxing when arguments are passed.

If the operations are math intensive or used as loop counters or other math oriented operations and not stored in collections (other than primitive arrays) I use the primitive. The same goes for all the other primitives except String which is a full fledged object.

Sager answered 17/10, 2015 at 17:43 Comment(0)
I
1

I guess it depends among other things on what you are using for accessing the database. With plain old JDBC you could do with ints, while an ORM could silently convert them to Integers anyway. And Integer would allow you to handle nulls.

Ivanna answered 8/1, 2009 at 9:45 Comment(0)
C
0

int can't be cast to the String with using the toString or (String).

Integer can cast to String with toString or (String) and it can handle null.

Calia answered 28/11, 2012 at 11:56 Comment(2)
You can use String.valueOf(int) to "cast" an int to String. As @Adeel answer points out, being able to handle 'null' is the only advantage here.Crimp
I'm not sure what funky compiler you're using but you cannot cast an Integer to String, ever.Insphere
M
0

If you want to check for a null value then Integer 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.

public class IntegerCompare {

    public static void main(String[] args) {
        int a = 1000;
        int b = 1000;

        Integer c = 1000;
        Integer d = 1000;

        if (a == b) {
            System.out.println("int Value Equals");

        }
        if (c == d) {
            System.out.println("Integer value Equals");

        } else {

            System.out.println("Integer Value Not Equals");
        }
    }
}
Muscolo answered 12/7, 2017 at 10:3 Comment(0)
A
0

One scenario to cover would be validation.

Imagine we have the following class:

class Foo{
    @Min(value = 10)
    int val;
}

If the user doesn't provide a value for val in the request, we will get a nasty NumberFormatException.

If int is replaced with Integer, we can use @NotNull and resolve this issue more gracefully.

Atonement answered 5/3, 2019 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.