整数自动拆箱和自动装箱会带来性能问题吗?
我们目前正在使用 x++;
进行一些迭代和其他操作,其中 x
是 Integer
而不是 int
。
我们系统上的某些用户操作可能会重复操作,但不会像数学应用程序那样太复杂或太多,每个用户事务最多可达 10000 次。
这种拆箱和稍后的装箱是否会影响我们的性能一些明显的毫秒?
We are currently doing some iterations and other operations using x++;
where x
is an Integer
and not an int
.
Operations may be repeated throughout some user operations on our system but nothing too complex or numerous like a Mathematical application, maximum up to 10000 times per user transaction..
Will this unboxing and later boxing affect our performance by some noticeable milliseconds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://download.oracle.com/javase/1.5.0/docs/ guide/language/autoboxing.html
“结果列表的性能可能很差,因为它在每次获取或设置操作时都会进行装箱或拆箱。对于偶尔使用来说,它足够快,但这是愚蠢的将其用于性能关键的内部 那么什么时候
应该使用自动装箱和拆箱呢?仅当引用类型和基元之间存在“阻抗不匹配”时才使用它们,例如,当您必须将数值放入集合中时,使用自动装箱和拆箱是不合适的。科学计算或其他性能敏感的数字代码的拆箱不能替代 int;自动装箱和拆箱模糊了基本类型和引用类型之间的区别,但它们并没有消除它。
http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
"The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It is plenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop.
So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it."
是的,有性能影响。为
++x
生成的等效代码涉及每次创建一个新的 Integer 对象。 x++ 另外创建了一个临时变量来存储先前的整数引用和一些操作。您可以通过反汇编类文件来验证这一点。Yes, there is a performance impact. The equivalent code produced for
++x
involves creating a new Integer object each time.x++
additionally creates a temporary variable to store the previous integer reference, and some manipulation. You can verify this by disassembling the class file.自动装箱的速度取决于您使用的 JVM 版本、您正在使用的实际数字的范围以及您的 GC 设置。请参阅这篇关于(非)拳击性能的非常有趣的深入文章。
基本上,JVM 缓存了许多 Integer 对象,因此不需要每次都创建“公共”对象。您可以配置此缓存大小。
至于具体问题:如果使用原语与自动装箱相比,您的操作会慢毫秒吗?这完全取决于列表的大小以及调用的频率。测试原始替代方案的性能应该很容易(我认为!)。
The speed of auto-boxing depends on the JVM version you're using, the range of the actual numbers you're working with, and your GC settings. See this really interesting in-depth article on (un)boxing performance.
Basically, the JVM caches a number of the Integer objects so it doesn't need to create the "common" ones every time. You can configure this cache size.
As for the specific question: Will your operation be milliseconds slower if you use primitives versus autoboxing? This entirely depends on the size of the list and how often it gets called. It should be easy (i think!) to test the primitive alternative's performance.