Frage

Ich muss ein Datenübertragungsobjekt erstellen, das ich zum Speichern der aus der Datenbank abgerufenen Datensätze verwenden werde. In diesem Datenübertragungsobjekt muss ich ein numerisches Feld deklarieren. Für das, was man besser ist - int oder Ganze Zahl

Wenn ich das Feld als Ganzzahl definiere, wird es aufgrund des Typs "Ganzzahl" einen Leistungsauswirkungen geben, wenn ich mehr als 2000 Datensätze von DB abrufen werde!?

Danke im Voraus.

War es hilfreich?

Lösung

Integer ist eine bessere Option, da es umgehen kann null; zum int, null würde werden 0, schweigend, wenn resultSet.getInt(..) wird genutzt. Andern null zu einer primitiven Eigenschaft ".

Leistung ist hier von geringem Anliegen.

  • wenn du wählst int, Sie werden letztendlich zusätzlichen Handhabungscode hinzufügen. Und das würde dir nicht viel zugute kommen. Ihr Code ist nicht sauber und unkompliziert, viel Boiler-Plate-Code, und Sie würden nicht einmal Leistung erzielen.
  • Lassen Sie mich klarstellen, dass Null für Datenbanken nicht gleich ist wie Null. Manchmal trittst du am Ende ein 0, wo null war beabsichtigt. Stellen Sie sich den Fall vor, in dem der Benutzer ein Formular eingereicht hat und keinen Wert für den Wert liefert int. Sie werden am Ende kommen 0 standardmäßig. Es macht Sinn oder tut das wirklich, wenn dieses Feld ist not null in der Datenbank.

Andere Tipps

Sie sollten Ihre Entscheidung wirklich basierend auf dem, was Sie für Ihr Objekt benötigen, und nicht die Leistungskosten treffen. Die Entscheidung auf der Leistung sollte erfolgen, sobald ein Geschwindigkeitsproblem mit einem Profiler identifiziert wurde - der Wurzel aller Bösen und all dem.

Schauen Sie sich einige der Funktionen beider an und verwenden Sie diese für Ihre Entscheidung, z. B. für Ihre Entscheidung

  • Integer kann sein null, int kann nicht. So ist das int in dem Db a Nullable aufstellen?
  • Benötigen Sie Zugriff auf die Integer Klassenmethoden?
  • Machst du Arithmetik?

Persönlich entscheide ich mich immer für den Primitiv über dem Wrapper. Aber das ist nur eine Präferenzsache, anstatt auf einem technischen Verdienst zu beruhen.

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

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.

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

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.

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.

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.

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.

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");
        }
    }
}

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top