Java 使用哪一个,int 或 Integer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/423704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:26:49  来源:igfitidea点击:

Which one to use, int or Integer

javadatabaseperformancetypesprimitive

提问by Veera

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 - intor Integer

我需要创建一个数据传输对象,用于存储从数据库中检索到的记录。在这个数据传输对象中,我需要声明一个数字字段。对于哪个更好 - intInteger

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!?

如果我将字段定义为整数,如果我要从数据库中检索超过 2000 条记录,是否会因为“整数”类型而对性能产生任何影响!?

Thanks in advance.

提前致谢。

采纳答案by Adeel Ansari

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

Integer是更好的选择,因为它可以处理null;for int,null会变成0, 默默地,如果resultSet.getInt(..)被使用。否则,它可能会抛出一些异常,例如“无法设置null为原始属性”。

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 nullwas intended. Imagine the case where user submitted a form, and doesn't supply any value for int. You will end up getting 0by default. It makes sense, or does that really, when that field is not nullin the database.
  • 如果您选择int,您最终将添加额外的处理代码;这对你没有多大好处。你的代码不会干净和直接,会有很多样板代码,你甚至不会获得性能。
  • 让我说清楚,对于数据库,null 与零不同。有时,您最终会进入0null预期的位置。想象一下用户提交了一个表单,并且没有为 提供任何值的情况int。你最终会得到0默认。当该字段not null在数据库中时,这是有道理的,或者确实如此。

回答by Mehrdad Afshari

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

Integer理论上比 慢int,但是除非您处理数字,否则性能影响应该很小。此外,JIT 优化将减少性能损失。

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

在原始类型或引用类型方面使用更适合您的情况的一种。

回答by agnul

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 Integersanyway. And Integer would allow you to handle nulls.

我想这取决于您用于访问数据库的内容。使用普通的旧 JDBC,您可以使用ints,而 ORM 可以默默地将它们转换为Integers无论如何。Integer 将允许您处理nulls

回答by tddmonkey

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.

查看两者的一些功能并将其用于您的决定,例如

  • Integercan be null, intcannot. So is the intin the DBa Nullablefield?
  • Do you need access to the Integerclass methods?
  • Are you doing arithmetic?
  • Integer可以nullint不能。那么int数据库中是一个Nullable字段吗?
  • 您需要访问Integer类方法吗?
  • 你在做算术吗?

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

就个人而言,我总是选择原始而不是包装器。但这只是一种偏好,而不是基于任何技术优点。

回答by Andrzej Doyle

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.

在我看来,将某物声明为 int 还是 Integer 的选择简单归结为 null 是否是它的有效值。自动装箱(和自动拆箱)将处理任何转换问题,其中数字必须是一种或另一种类型。在几乎所有情况下,性能(正如已经指出的那样)也不太可能引人注目。

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 haveto 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 应该是自然的选择,并且无论如何都可能是性能最高的。如果您需要能够存储空值,那么您必须使用 Integer(并确保没有空引用被自动拆箱用于仅采用整数的方法,因为这将导致 NullPointerException)。

回答by Peter Lawrey

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.

给你一个想法,2000 Integer 会给你的查询增加大约 0.5 毫秒。如果您必须序列化这些数据,它可能会添加更多。

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

但是,正确性应该是第一位的。速度非常快是没有意义的,但这是错误的。您必须考虑空值以及如何处理它们。(除非该列不是 NULL)您可以使用 Integer.MIN___VALUE 或者您可以使用long字段而不是 int 并使用 Long.MIN_VALUE 为空。尽管它比 int 大,但它仍然比 Integer 小很多倍,效率也更高。

回答by Amine

int is 10x faster than integer

int 比整数快 10 倍

we test this code with jetm performance library

我们使用 jetm 性能库测试此代码

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

结果:
test:objects 10.184
test:primitives 1.151

回答by Deepak

intcan't be cast to the Stringwith using the toStringor (String).

int不能String使用toStringor强制转换为with (String)

Integercan cast to Stringwith toStringor (String)and it can handle null.

Integer可以投射到StringwithtoString(String)并且它可以处理null.

回答by peterk

intis used by java for most all calculations. Integeris used in all forms of Collections except for primitive arrays.

int由 java 用于大多数所有计算。 Integer用于所有形式的集合,除了原始数组。

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)

使用大量临时整数和垃圾收集器并在后台使用不可分析的 CPU,这将导致一切普遍放缓。每秒丢弃太多临时文件将导致 CG 进入紧急“我现在需要内存”模式,这可能导致延迟关键应用程序(即:实时交互式图形、物理设备控制器或通信)的停顿

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.

所以对我来说,如果我有很多嵌套调用,它们不做数学运算但访问很多集合,例如使用映射的键,我使用 Integer 以避免在传递参数时大量自动装箱。

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.

如果操作是数学密集型的,或者用作循环计数器或其他面向数学的操作,而不是存储在集合中(原始数组除外),我将使用原语。除了 String 是一个完整的对象之外,所有其他原语也是如此。

回答by Pankaj Singla

If you want to check for a nullvalue then Integeris 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.

如果你想检查一个null值,那么Integer最好,但如果你想比较整数,那么 int 可能更好。在下面的示例中,我使用整数 c=1000 和 d=1000 并比较它返回 false 但在 int 的情况下它们将返回 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");
        }
    }
}