比较int和Integer的性能 [英] Comparing Performance of int and Integer
问题描述
哪一个最适合编程 - int
或整数
?特别是每个人都在做同样的任务?
Which one is best in programming - int
or Integer
? Especially whenever both are doing the same task?
我正在用Java编写一个应用程序。在原始数据类型的大多数地方,我使用 int
;对于对象,我使用 Integer
。所以我很困惑 - 哪一个是最好的地方,我们必须使用对象。
I am writing an application in Java. In most of the places of primitive data types, I use int
; and for objects, I use Integer
. So I am confused- which one is the best in places, where we have to use objects.
根据性能,哪一个最适合Java应用程序?
According to performance, which one is best for a Java application?
推荐答案
尽可能使用 int
,并使用 Integer
需要时。由于 int
是一个原语,它会更快。现代JVM知道如何使用自动装箱优化 Integer
,但如果您正在编写性能关键代码, int
是要走的路。
Use int
when possible, and use Integer
when needed. Since int
is a primitive, it will be faster. Modern JVMs know how to optimize Integer
s using auto-boxing, but if you're writing performance critical code, int
is the way to go.
看看这个和这篇文章。虽然你不应该将它们视为绝对真理,但它们确实表明对象将比原始对象慢。
Take a look at this and this article. Although you shouldn't treat them as absolute truths, they do show that objects will be slower than their primitive counterparts.
所以,使用 int
尽可能(我会重复自己:如果你正在编写性能关键代码)。如果某个方法需要Integer,请改用它。
So, use int
whenever possible (I will repeat myself: if you're writing performance critical code). If a method requires an Integer, use that instead.
如果您不关心性能并希望以面向对象的方式执行所有操作,请使用整数
。
If you don't care about performance and want to do everything in an object oriented fashion, use Integer
.
这篇关于比较int和Integer的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!